码迷,mamicode.com
首页 > 其他好文 > 详细

DJANGO-增删改查

时间:2019-07-18 19:25:36      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:info   with   写法   xxxxx   like   hhhh   多表   efault   字段   

class Department(models.Model):
    title = models.CharField(max_length=32,  null=True)
class UserInfo(models.Model):
    id = models.AutoField(primary_key=True)
    uname = models.CharField(max_length=32, null=True)
    age = models.CharField(max_length=32, null=True)
    email = models.CharField(max_length=32, default="")
    ud = models.ForeignKey("Department", null=True)  ### 加上一个ud_id

单表的增删改查
  ##### 单表 的增删改查
    ### 增加
    # models.Department.objects.create(title="保安部")
    # models.Department.objects.create(title="开发部")
    ### 查询
    ### 查询所有
    # res = models.Department.objects.all()
    ### <QuerySet [<Department: Department object>, <Department: Department object>]>
    # for row in res:
    #     print(row.id, row.title)
    ### 指定字段查询 values
    ### select title from department ;
    # res = models.Department.objects.values("title").all()
    # ### <QuerySet [{‘title‘: ‘保安部‘}, {‘title‘: ‘开发部‘}, {‘title‘: ‘开发部‘}]>
    # for row in res:
    #     print(row[‘title‘])
    ### 指定字段查询 value_list
    # res = models.Department.objects.values_list("title").all()
    # ### <QuerySet [(‘保安部‘,), (‘开发部‘,), (‘开发部‘,)]>
    # print(res)
    ### select * from xxx where title = "开发部"
    # res = models.Department.objects.filter(title=‘开发部‘).all()
    #
    # print(res)
    # res = models.Department.objects.filter(id__lt = 3)   ### little than
    # res = models.Department.objects.filter(id__gt = 3)  ###  greater than
    ## 取第一条数据
    # res = models.Department.objects.all().first()
    # print(res)
    ### 删:
    # models.Department.objects.filter(id=3).delete()
    ### 更新
    # models.Department.objects.filter(id=2).update(title=‘xxxx‘)
一对多的增删改查
 #########################################一对多表########
    ### 增加
    # models.UserInfo.objects.create(uname = "zekai3", age=15, email="dddd@qq.com", ud_id=2)
    # models.UserInfo.objects.create(uname = "zekai4", age=16, email="gggg@qq.com", ud_id=2)
    # models.UserInfo.objects.create(uname = "zekai5", age=18, email="hhhh@qq.com", ud_id=1)
    # info = {"uname":‘zekai2‘, ‘age‘:13, "email":‘123@qq.com‘, "ud_id":2}
    # models.UserInfo.objects.create(**info)

    ### 查询
    ### 正向查询
    # res = models.UserInfo.objects.all()
    # for row in res:
    #     print(row.id, row.uname, row.age, row.ud.title)
    ### 反向查询
    ### 写法: 小写的表名_set.all()
    # res = models.Department.objects.all()
    # for row in  res:
    #     print(row.title, row.userinfo_set.all())
    ### 删:
    # models.Department.objects.filter(id=3).delete()
    ### 更新
    # models.Department.objects.filter(id=2).update(title=‘xxxx‘)

    ### 神奇的双下画线
    res = models.UserInfo.objects.values(‘id‘, ‘uname‘, "ud__title").all()
    print(res)
    <QuerySet [{‘id‘: 1, ‘name‘: ‘zz‘, ‘ud__title‘: ‘保安部‘}, {‘id‘: 2, ‘name‘: ‘xx‘, ‘ud__title‘: ‘保安部‘}, {‘id‘: 3, ‘name‘: ‘bb‘, ‘ud__title‘: ‘xxx‘}, {‘id‘: 4, ‘name‘: ‘qq‘, ‘ud__title‘: ‘xxx‘},
    res = models.UserInfo.objects.values_list(‘id‘, ‘uname‘, "ud__title").all()
    print(res)
    <QuerySet [(1, ‘zz‘, ‘保安部‘), (2, ‘xx‘, ‘保安部‘), (3, ‘bb‘, ‘xxx‘), (4, ‘qq‘, ‘xxx‘), (7, ‘zzz‘, ‘卫生部‘)}
#####多对多
class Boy(models.Model):
    name = models.CharField(max_length=32, null=True)
    g = models.ManyToManyField(‘Girl‘, null=True)    django 自动生成的第三张表
class Girl(models.Model):
    nick = models.CharField(max_length=32, null=True)
    ### 1. 查询和 勾洋 约会的 姑娘
    # res = models.Boy.objects.filter(name=‘勾洋‘).first()
    # # print(res) ### Boy object
    # ### 反向查询 love中的相亲记录
    # love_list = res.love_set.all() ## <QuerySet [<Love: Love object>, <Love: Love object>]>
    # for obj in love_list:
    #     ### 正向查询 girl表中的nick
    #     print(obj.g.nick)
    #### 2.查询和 勾洋 约会的 姑娘
    # res = models.Love.objects.filter(b__name=‘勾洋‘).all()
    # print(res) ## <QuerySet [<Love: Love object>, <Love: Love object>]>
    # for obj in res:
    #     print(obj.g.nick)
    ### 3.查询和 勾洋 约会的 姑娘
    # res = models.Love.objects.filter(b__name=‘勾洋‘).values("g__nick")
    # print(res)
======================================================
# class Love(models.Model):
#     b = models.ForeignKey("Boy", null=True)   自己建的第三张表
#     g = models.ForeignKey("Girl", null=True)
#
#     class Meta:
#         unique_together = [      联合唯一索引
#             (‘b‘,  ‘g‘)
#         ]
### 自己写的第三张表
    # models.Love.objects.create(b_id=1, g_id=2)
    ### django
    ### 添加
    obj = models.Boy.objects.filter(name=‘谢增城‘).first()
    # print(obj)### Boy object
    # obj.g.add(3)
    # obj.g.add(*[1,2])
    ### 重置
    # obj.g.set([4])
    ### 查询
    # obj = models.Boy.objects.filter(name=‘谢增城‘).first()
    # res = obj.g.all()
    # print(res) ## <QuerySet [<Girl: Girl object>, <Girl: Girl object>, <Girl: Girl object>]>
    # for obj  in res:
    #     print(obj.nick)
    ## 删除
    obj = models.Boy.objects.filter(name=‘谢增城‘).first()
    obj.g.clear()
应该使用哪个?
     注意: ManyToManyField 只能生成两个字段(boy_id 和 girl_id)
     根据自己的业务逻辑去写
===========================================================     
e.增
   ### 插入一条数据
   models.xxx.objects.create(name=‘xxx‘)
   
   ### 插入多条数据
   obj = [
    models.UserInfo(name=‘zekai‘, age=12,  ut_id=2),
    models.UserInfo(name=‘xxxxx‘, age=13,  ut_id=2),
    models.UserInfo(name=‘dsadsa‘, age=14,  ut_id=1),
    models.UserInfo(name=‘gfdgfdg‘, age=24,  ut_id=2),
    models.UserInfo(name=‘tretre‘, age=45,  ut_id=3),
    models.UserInfo(name=‘gfdgfd‘, age=42,  ut_id=2),
   ]
   models.UserInfo.objects.bulk_create(obj)
  f.删
   models.xxxx.objects.all().delete()
   models.xxxx.objects.filter(name=‘kkk‘).delete()
   
   ps:
    ut = models.ForeignKey("UserType", null=True, on_delete=models.CASCADE)
    CASCADE: 设置级联删除
    SET_NULL : 取消级联删除
  
  g.改
   
   models.userinfo.objects.filter(xxxx).update()
级联删除:在一对多关系中,例如主机对应多个role,每个role对应1个主机,
当删除了某个主机时候,发现对应的role也被删除了
on_delete=models.CASCADE
CASCADE: 设置级联删除
SET_NULL : 取消级联删除
            
=========================================
高级查询
 ## 1. in
    # res = models.UserInfo.objects.filter(id__in=[1,2,3])
    # print(res)
    ## 2. not in
    # res = models.UserInfo.objects.exclude(id__in=[1,2,3])
    # print(res)
    ## 3. like
    ## where name like ‘ze%‘ ## 以ze开头的所有的数据
    ### startswith: 以 某单词开头
    ### istartswith : ignore (忽略)  以 某单词开头 忽略大小写
    # res = models.UserInfo.objects.filter(name__startswith="ze")
    # res = models.UserInfo.objects.filter(name__istartswith="ze")
    # print(res)
    ## where  name  like ‘%ze‘
    ## endswith : 以 某个单词结尾
    ## iendswith:  ignore (忽略)  以 某单词结尾 忽略大小写
    # res = models.UserInfo.objects.filter(name__endswith=‘ze‘)
    ## where name like "%ze%"
    ### contains : 包含某一个单词
    ### icontains: 包含某一个单词 不区分大小写
    # models.UserInfo.objects.filter(name__contains=‘ze‘)
    ### 4. between.. and..
    ### models.UserInfo.objects.filter(id__range=[1,2])
    ### 5. limit 10, 20
    # models.UserInfo.objects.all()[开始位置:结束位置]
    # models.UserInfo.objects.all()[0:10]
    # models.UserInfo.objects.all()[10:20]
    ### 6. order by age asc, name desc
    # res = models.UserInfo.objects.all().order_by(‘id‘) ## 默认升序
    ### 前面加一个 ‘-’ 代表 降序
    # res = models.UserInfo.objects.all().order_by(‘-id‘,‘name‘)
    # print(res.query)
    ### 7. group by
    # from django.db.models import Count, Max, Min, Sum
    # res = models.UserInfo.objects.values(‘name‘).annotate(xxx=Count(‘id‘))
    # print(res.query)
    # SELECT "app01_userinfo"."id", COUNT("app01_userinfo"."name") AS "xxx"
    # FROM "app01_userinfo"
    # GROUP BY "app01_userinfo"."id";

    #### 8. only: 只取某一个列的值
    ## SELECT "app01_userinfo"."id", "app01_userinfo"."name", "app01_userinfo"."age" FROM "app01_userinfo"
    # res = models.UserInfo.objects.only(‘name‘,  ‘age‘).all()
    # print(res) ## <QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
    ### 9. defer: 除了这几列之外的所有列的值
    ### SELECT "app01_userinfo"."id", "app01_userinfo"."ut_id" FROM "app01_userinfo"
    # res = models.UserInfo.objects.defer(‘id‘,‘name‘, ‘age‘).all()
    # print(res.query)
    ### 10.using: 想要使用哪个数据库, 就将这个数据库的配置名称写到using中
    # models.UserInfo.objects.all().using("xxxx")

    ### 11. 表中总共多少条数据
    # res = models.UserInfo.objects.count()
    # print(res)
    ### 12. 第一条数据
    # res = models.UserInfo.objects.first()
    # print(res)
    ## 13.最后一条数据
    # res = models.UserInfo.objects.last()

    ## 14.gt lt
    # res = models.UserInfo.objects.filter(id__gt=3)
    # res = models.UserInfo.objects.filter(id__gte=3)
    # res = models.UserInfo.objects.filter(id__lt=3)
    # res = models.UserInfo.objects.filter(id__lte=3)
    ### 15. and操作
    # res =  models.UserInfo.objects.filter(id=1, name=‘zekai‘)
    # print(res.query)
    ### 16.or操作
    # from django.db.models import Q
    # res = models.UserInfo.objects.filter( Q(Q(id=1) | Q(name=‘zekai‘)) & Q(name=‘xxxx‘)  )
    # print(res.query)
    ### 17. 在原来的基础上更新值
    # from django.db.models import F
    # models.UserInfo.objects.update(age = F(‘age‘) + 1)
    ## 18。原生sql
    # from django.db import  connection
    # cursor = connection.cursor()
    # cursor.execute("select * from app01_userinfo where id=%s", [1,])
    # # res = cursor.fetchall()
    # # res = cursor.fetchone()
    # # print(res)
    ## 19. 原生sql
    # models.UserInfo.objects.raw(‘select * from app01_userinfo‘)

DJANGO-增删改查

标签:info   with   写法   xxxxx   like   hhhh   多表   efault   字段   

原文地址:https://www.cnblogs.com/fan-1994716/p/11209401.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!