zoukankan      html  css  js  c++  java
  • ORM操作models一对多、多对多关系

    ORM操作 

    单表、一对多表操作

     1 from django.db import models
     2 
     3 
     4 class UserGroup(models.Model):
     5     title = models.CharField(max_length=32)
     6 
     7 
     8 class UserInfo(models.Model):
     9     username = models.CharField(max_length=32)
    10     password = models.CharField(max_length=64)
    11     # age = models.IntegerField(null=True)
    12     age = models.IntegerField(default=1)  # 处理这种问题直接可以设置成空或者默认给个值 因为此时在数据库有数据
    13     ug = models.ForeignKey("UserGroup", on_delete=models.CASCADE, null=True)
    models.py
     1  # 新增
     2     # models.UserGroup.objects.create(title="销售部")
     3     # models.UserInfo.objects.create(username='孙大圣', password='pwd', age=18, ug_id=1)
     4     # 
     5     # 查找
     6     # group_list = models.UserGroup.objects.all()  # group_list是QuerySet类型  相当于一个列表
     7     # for row in group_list:
     8     #     print(row.id, row.title)
     9     # 
    10     # group_list = models.UserGroup.objects.filter(id=1)
    11     # group_list = models.UserGroup.objects.filter(id__gt=1)#大于
    12     # group_list = models.UserGroup.objects.filter(id__lt=1) #小于
    13     # 
    14     # 删除
    15     # models.UserGroup.objects.filter(id=2).delete()
    16     # 
    17     # 更新
    18     # models.UserGroup.objects.filter(id=2).update(title='公关部')
    19     # filter里边的条件如果多个默认是and关系取
    20     # models.UserType.objects.all().count()总数量
    21     # models.UserType.objects.all().update()改
    22     # models.UserType.objects.all().delete()删除
    23     # models.UserType.objects.all()[1:10]
    基本操作

    正反操作+高级+其它

     1         # 获取个数
     2         #
     3         # models.Tb1.objects.filter(name='seven').count()
     4 
     5         # 大于,小于
     6         #
     7         # models.Tb1.objects.filter(id__gt=1)              # 获取id大于1的值
     8         # models.Tb1.objects.filter(id__gte=1)              # 获取id大于等于1的值
     9         # models.Tb1.objects.filter(id__lt=10)             # 获取id小于10的值
    10         # models.Tb1.objects.filter(id__lte=10)             # 获取id小于10的值
    11         # models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 获取id大于1 且 小于10的值
    12 
    13         # in
    14         #
    15         # models.Tb1.objects.filter(id__in=[11, 22, 33])   # 获取id等于11、22、33的数据
    16         # models.Tb1.objects.exclude(id__in=[11, 22, 33])  # not in
    17 
    18         # isnull
    19         # Entry.objects.filter(pub_date__isnull=True)
    20 
    21         # contains
    22         #
    23         # models.Tb1.objects.filter(name__contains="ven")
    24         # models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
    25         # models.Tb1.objects.exclude(name__icontains="ven")
    26 
    27         # range
    28         #
    29         # models.Tb1.objects.filter(id__range=[1, 2])   # 范围bettwen and
    30 
    31         # 其他类似
    32         #
    33         # startswith,istartswith, endswith, iendswith,
    34 
    35         # order by
    36         #
    37         # models.Tb1.objects.filter(name='seven').order_by('id')    # asc
    38         # models.Tb1.objects.filter(name='seven').order_by('-id')   # desc
    39 
    40         # group by
    41         #
    42         # from django.db.models import Count, Min, Max, Sum
    43         # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
    44         # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"
    45 
    46         # limit 、offset
    47         #
    48         # models.Tb1.objects.all()[10:20]
    49 
    50         # regex正则匹配,iregex 不区分大小写
    51         #
    52         # Entry.objects.get(title__regex=r'^(An?|The) +')
    53         # Entry.objects.get(title__iregex=r'^(an?|the) +')
    54 
    55         # date
    56         #
    57         # Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
    58         # Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
    59 
    60         # year
    61         #
    62         # Entry.objects.filter(pub_date__year=2005)
    63         # Entry.objects.filter(pub_date__year__gte=2005)
    64 
    65         # month
    66         #
    67         # Entry.objects.filter(pub_date__month=12)
    68         # Entry.objects.filter(pub_date__month__gte=6)
    69 
    70         # day
    71         #
    72         # Entry.objects.filter(pub_date__day=3)
    73         # Entry.objects.filter(pub_date__day__gte=3)
    74 
    75         # week_day
    76         #
    77         # Entry.objects.filter(pub_date__week_day=2)
    78         # Entry.objects.filter(pub_date__week_day__gte=2)
    79 
    80         # hour
    81         #
    82         # Event.objects.filter(timestamp__hour=23)
    83         # Event.objects.filter(time__hour=5)
    84         # Event.objects.filter(timestamp__hour__gte=12)
    85 
    86         # minute
    87         #
    88         # Event.objects.filter(timestamp__minute=29)
    89         # Event.objects.filter(time__minute=46)
    90         # Event.objects.filter(timestamp__minute__gte=29)
    91 
    92         # second
    93         #
    94         # Event.objects.filter(timestamp__second=31)
    95         # Event.objects.filter(time__second=2)
    96         # Event.objects.filter(timestamp__second__gte=31)
    进阶操作
     1 from django.db import models
     2 
     3 
     4 class UserType(models.Model):
     5     title = models.CharField(max_length=32)
     6 
     7 
     8 class UserInfo(models.Model):
     9     username = models.CharField(max_length=32)
    10     password = models.CharField(max_length=64)
    11     age = models.IntegerField()
    12     ut = models.ForeignKey('UserType', on_delete=models.CASCADE)
    13 
    14     def __str__(self):
    15         return '%s--%s' % (self.id, self.username)
    models.dy
     1     # 第一部分  连表操作 
     2     # from app01 import models
     3     # 获取
     4     # result = models.UserInfo.objects.all()
     5     # .all  .filter 都是QuerySet对象 [obj, obj] 里边放的就是数据库里边对应的每一行数据对象
     6     # for obj in result:
     7     #     print(obj.username, obj.age, obj.ut_id, obj.ut.title)  # 可以一直跨表下去但不要无限制 效率问题
     8 
     9     # UserInfo ut字段外键FK  正向操作
    10     # obj = models.UserInfo.objects.all().first()
    11     # print(obj.username, obj.age, obj.ut.title)
    12 
    13     # result = models.UserInfo.objects.all().values('id', 'username', 'ut__title')
    14     # 里边放的字典对象      以下两种方式本质上不能跨表 但是在取数据的时候用双下划线也可以做到跨表查询 神奇的__
    15     # <QuerySet [{'id': 1, 'username': '孙大圣', 'ut__title': '牛逼用户'}, {'id': 2, 'username': '唐和尚', 'ut__title': '二笔用户'}]>
    16     # for row in result:
    17         # print(row['username'], row['ut__title'])
    18 
    19     # result = models.UserInfo.objects.all().values_list('id', 'username')
    20     # 里边放元组对象
    21     # <QuerySet [(1, '孙大圣'), (2, '唐和尚'), (3, '猪八戒'), (4, '沙和尚')]>
    22     # print(result)
    23 
    24 
    25     # UserType 表名小写_set.all() 反向操作
    26     # obj = models.UserType.objects.all().first()
    27     # print(obj.id, obj.title, obj.userinfo_set.all())
    28     # for row in obj.userinfo_set.all():
    29     #     print(row.id, row.username)
    30 
    31     # result = models.UserType.objects.all()
    32     # for item in result:
    33     #     print(item.title, item.userinfo_set.all())
    34 
    35     # obj = models.UserType.objects.all().first()
    36     # result = obj.userinfo_set.all()
    37     # print(result)
    38 
    39     # models.UserType.objects.all().values('id', 'title')
    40     # models.UserType.objects.all().filter('还可以先加条件').values('id', 'title', 'userinfo') # 正反向操作都是可以先加条件再干
    41     # models.UserType.objects.all().values('id', 'title', 'userinfo__username')
    42     # values_list也一样  谁在前边,那么前边的表就会显示完  跟mysql里边左右连接一样
    连表操作之正反向
     1     # 高级操作
     2     # F Q extra
     3     # F操作
     4     # from django.db.models import F, Q
     5     # # F 批量对某个字段更新数据时用
     6     # models.UserInfo.objects.all().update(age=F("age")+1)
     7     #
     8     # # Q 构造复杂的查询条件
     9     # condition = {
    10     #     'id': 1,
    11     #     'username': 'root'
    12     # }
    13     # models.UserInfo.objects.filter(**condition)
    14     # models.UserInfo.objects.filter(Q(id=1) | Q(id__gt=3))
    15     # models.UserInfo.objects.filter(Q(id=1) & Q(id__gt=3))
    16     #
    17     # q1 = Q()
    18     # q1.connector = 'OR'
    19     # q1.children.append(('id__lt', 2))
    20     # q1.children.append(('id', 2))
    21     # q1.children.append(('id', 3))
    22     #
    23     # q2 = Q()
    24     # q2.connector = 'OR'
    25     # q2.children.append(('a1', 3))
    26     # q2.children.append(('a2', 4))
    27     # q2.children.append(('a3', 1))
    28     #
    29     # q3 = Q()
    30     # q3.connector = 'AND'
    31     # q3.children.append(('b1', 1))
    32     # q3.children.append(('b2', 2))
    33     # q1.add(q3, 'OR')
    34     #
    35     # con = Q()
    36     # con.add(q1, 'AND')
    37     # con.add(q2, 'AND')
    38     # # (id = 1 or id=2 or id=3 or (b1=1 and b2=2))  and (a1=3 or a2=4 or a3=1)
    39     # models.UserInfo.objects.filter(con)
    40     #
    41     # # extra(self, select=None, where=None, params=None, tables=None,order_by=None, select_params=None)
    42     # v = models.UserInfo.objects.all().extra(select={'n': "select count(1) from app01_usertype where id>%s and id<%s"}, select_params=[1, 4], order_by=['-id'])
    43     # for obj in v:
    44     #     print(obj.username, obj.id, obj.n)
    45     #
    46     # models.UserInfo.objects.extra(
    47     #     where=["id=1", "username='SB'"]
    48     # )
    49     # models.UserInfo.objects.extra(
    50     #     where=["id=1 or id=%s", "username=%s"],
    51     #     params=[1, 'SB']
    52     # )
    53     # v = models.UserInfo.objects.extra(
    54     #     tables=['app01_usertype'],  # 笛卡尔积
    55     #     where=['app01_usertype.id = app01_userinfo.ut_id']  # 加上这个条件又进一步的筛选
    56     # )
    57     # print(v.query)
    58     # # SELECT "app01_userinfo"."id", "app01_userinfo"."username", "app01_userinfo"."password", "app01_userinfo"."age", "app01_userinfo"."ut_id" FROM "app01_userinfo" , "app01_usertype" WHERE (app01_usertype.id = app01_userinfo.ut_id)
    59     #
    60     # # 执行原生SQL
    61     # from django.db import connection, connections
    62     # cursor = connection.cursor()  # cursor = connections['default'].cursor()  看配置文件数据库默认字段default如果有多个库,填库名称即可
    63     # cursor.execute("""SELECT * from app01_userinfo where id = %s""", [1])
    64     # row = cursor.fetchone()
    65     # row = cursor.fetchall()
    66     #
    67     # # def raw(self, raw_query, params=None, translations=None, using=None):
    68     # # models.UserInfo.objects.raw('select * from userinfo')
    69     # # 如果SQL是其他表时,必须将名字设置为当前UserInfo对象的主键列名
    70     # # models.UserInfo.objects.raw('select id as nid from 其他表')
    71     # # 为原生SQL设置参数
    72     # # models.UserInfo.objects.raw('select id as nid from userinfo where nid>%s', params=[12, ])
    73     # # 将获取的到列名转换为指定列名
    74     # # name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
    75     # # models.UserInfo.objects.raw('SELECT * FROM some_other_table', translations=name_map)
    76     # # 指定数据库
    77     # models.UserInfo.objects.raw('select * from userinfo', using="default")
    78     #
    79     # # 综合运用
    80     # result = models.UserInfo.objects.filter(id__gt=1).extra(
    81     #     where=['app01_userinfo.id<%s'],
    82     #     params=[100, ],
    83     #     tables=['app01_usertype'],
    84     #     order_by=['-app01_userinfo.id'],
    85     #     select={'uid': 1, 'uuid': "select count(1) from app01_userinfo where app01_userinfo.age<%s"},
    86     #     select_params=[20, ]
    87     # )
    88     # # SELECT (1) AS "uid", (select count(1) from app01_userinfo where app01_userinfo.age<20) AS "uuid", "app01_userinfo"."id", "app01_userinfo"."username", "app01_userinfo"."password", "app01_userinfo"."age", "app01_userinfo"."ut_id" 
    89     # # FROM "app01_userinfo" , "app01_usertype" WHERE ("app01_userinfo"."id" > 1 AND (app01_userinfo.id<100)) ORDER BY ("app01_userinfo".id) DESC
    90     # print(result.query)
    高级操作
     1     # 排序order_by
     2     # user_list = models.UserInfo.objects.all().order_by('-id', 'username')  # 倒序  从大到小
     3     # print(user_list)
     4     from django.db.models import Count, Sum, Max, Min, Avg
     5     # 分组annotate(根据某一个字段进行分组),(aggregate它是整张表聚合弄成一个组)
     6     # v = models.UserInfo.objects.values('ut_id').annotate(xxx=Count('id'))
     7     # print(v.query)  # SELECT "app01_userinfo"."ut_id", COUNT("app01_userinfo"."id") AS "xxx" FROM 
     8     # "app01_userinfo" GROUP BY "app01_userinfo"."ut_id"
     9     # result = models.UserInfo.objects.aggregate(k=Count('ut_id', distinct=True), n=Count('id'))
    10     # print(result)  # {'k': 3, 'n': 4}
    11 
    12 
    13     # 相当于having函数
    14     # filter在前在后不一样,在前面相当于表示where条件,后边再分组,最后在having就相当于mysql里边where>group_by>having
    15     # v = models.UserInfo.objects.values('ut_id').annotate(xxx=Count('id')).filter(xxx__gt=1)
    16     # SELECT "app01_userinfo"."ut_id", COUNT("app01_userinfo"."id") AS "xxx" FROM "app01_userinfo" 
    17     # GROUP BY "app01_userinfo"."ut_id" HAVING COUNT("app01_userinfo"."id") > 1
    18     # print(v.query)
    19     # 去重注意了distinct
    20     # 在django里边数据源的不同,有不同的搞法 连mysql sqlite distinct()里边不能传参数
    21     # models.UserInfo.objects.values('id').distinct()
    22     # select distinct id from userinfo
    23 
    24     # 而在PostgreSQL参数直接传进去
    25     # models.UserInfo.objects.distinct('id')
    26     # select distinct id from userinfo
    27 
    28     # 反转操作必须跟排序同时用才起作用reverse 把id升序 username倒序
    29     # models.UserInfo.objects.all().order_by('-id', 'username').reverse()
    30 
    31     # only注意 defer
    32     # v = models.UserInfo.objects.all().only('id', 'username')
    33     # v = models.UserInfo.objects.all().defer('username')  # 排除
    34     # for obj in v:
    35         # print(obj.id, obj.username, obj.age)  # 注意如果再拿obj.age又要发sql请求这样会降低效率
    36 
    37     # using指定在哪个数据库取数据
    38     # models.UserInfo.objects.all().using('db2')  前提有这张表这个数据库 不写参数默认'default'在settings里边配多个库可以
    39 
    40     # get方法少用 取不到直接报错,取多个也报错
    41 
    42     # create
    43     # models.UserType.objects.create(title='xxx')
    44     # models.UserType.objects.create(**{"title": 'xxx'})
    45     # obj = models.UserType(title='xxx') # 临时的未提交数据库
    46     # obj.save()  # 提交
    47 
    48     # bulk_create批量增加
    49     # def bulk_create(self, objs, batch_size=None):
    50     # batch_size表示一次插入的个数  不要大量的批量加  最多999个
    51     # objs = [
    52     #     models.UserInfo(name='r11'),
    53     #     models.UserInfo(name='r22')
    54     # ]
    55     # models.UserInfo.objects.bulk_create(objs, 10)
    56 
    57     # def get_or_create(self, defaults=None, **kwargs):
    58     # 如果存在,则获取,否则,创建
    59     # defaults 指定创建时,其他字段的值
    60     # update_or_create一样的操作
    61     # obj, created = models.UserInfo.objects.get_or_create(username='root1',password='123456',
    62     #                                                     defaults={'age': 18, 'ut_id': 2, 'password': '123456'})
    63 
    64     # in_bulk根据主键id进行查找
    65     # id_list = [11, 21, 31]
    66     # models.UserInfo.objects.in_bulk(id_list)
    67 
    68     #  exists是否存在
    其它
      1 ##################################################################
      2 # PUBLIC METHODS THAT ALTER ATTRIBUTES AND RETURN A NEW QUERYSET #
      3 ##################################################################
      4 
      5 def all(self)
      6     # 获取所有的数据对象
      7 
      8 def filter(self, *args, **kwargs)
      9     # 条件查询
     10     # 条件可以是:参数,字典,Q
     11 
     12 def exclude(self, *args, **kwargs)
     13     # 条件查询
     14     # 条件可以是:参数,字典,Q
     15 
     16 def select_related(self, *fields)
     17      性能相关:表之间进行join连表操作,一次性获取关联的数据。
     18      model.tb.objects.all().select_related()
     19      model.tb.objects.all().select_related('外键字段')
     20      model.tb.objects.all().select_related('外键字段__外键字段')
     21 
     22 def prefetch_related(self, *lookups)
     23     性能相关:多表连表操作时速度会慢,使用其执行多次SQL查询在Python代码中实现连表操作。
     24             # 获取所有用户表
     25             # 获取用户类型表where id in (用户表中的查到的所有用户ID)
     26             models.UserInfo.objects.prefetch_related('外键字段')
     27 
     28 
     29 
     30             from django.db.models import Count, Case, When, IntegerField
     31             Article.objects.annotate(
     32                 numviews=Count(Case(
     33                     When(readership__what_time__lt=treshold, then=1),
     34                     output_field=CharField(),
     35                 ))
     36             )
     37 
     38             students = Student.objects.all().annotate(num_excused_absences=models.Sum(
     39                 models.Case(
     40                     models.When(absence__type='Excused', then=1),
     41                 default=0,
     42                 output_field=models.IntegerField()
     43             )))
     44 
     45 def annotate(self, *args, **kwargs)
     46     # 用于实现聚合group by查询
     47 
     48     from django.db.models import Count, Avg, Max, Min, Sum
     49 
     50     v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id'))
     51     # SELECT u_id, COUNT(ui) AS `uid` FROM UserInfo GROUP BY u_id
     52 
     53     v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id')).filter(uid__gt=1)
     54     # SELECT u_id, COUNT(ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1
     55 
     56     v = models.UserInfo.objects.values('u_id').annotate(uid=Count('u_id',distinct=True)).filter(uid__gt=1)
     57     # SELECT u_id, COUNT( DISTINCT ui_id) AS `uid` FROM UserInfo GROUP BY u_id having count(u_id) > 1
     58 
     59 def distinct(self, *field_names)
     60     # 用于distinct去重
     61     models.UserInfo.objects.values('nid').distinct()
     62     # select distinct nid from userinfo
     63 
     64     注:只有在PostgreSQL中才能使用distinct进行去重
     65 
     66 def order_by(self, *field_names)
     67     # 用于排序
     68     models.UserInfo.objects.all().order_by('-id','age')
     69 
     70 def extra(self, select=None, where=None, params=None, tables=None, order_by=None, select_params=None)
     71     # 构造额外的查询条件或者映射,如:子查询
     72 
     73     Entry.objects.extra(select={'new_id': "select col from sometable where othercol > %s"}, select_params=(1,))
     74     Entry.objects.extra(where=['headline=%s'], params=['Lennon'])
     75     Entry.objects.extra(where=["foo='a' OR bar = 'a'", "baz = 'a'"])
     76     Entry.objects.extra(select={'new_id': "select id from tb where id > %s"}, select_params=(1,), order_by=['-nid'])
     77 
     78  def reverse(self):
     79     # 倒序
     80     models.UserInfo.objects.all().order_by('-nid').reverse()
     81     # 注:如果存在order_by,reverse则是倒序,如果多个排序则一一倒序
     82 
     83 
     84  def defer(self, *fields):
     85     models.UserInfo.objects.defer('username','id')
     86  87     models.UserInfo.objects.filter(...).defer('username','id')
     88     #映射中排除某列数据
     89 
     90  def only(self, *fields):
     91     #仅取某个表中的数据
     92      models.UserInfo.objects.only('username','id')
     93  94      models.UserInfo.objects.filter(...).only('username','id')
     95 
     96  def using(self, alias):
     97      指定使用的数据库,参数为别名(setting中的设置)
     98 
     99 
    100 ##################################################
    101 # PUBLIC METHODS THAT RETURN A QUERYSET SUBCLASS #
    102 ##################################################
    103 
    104 def raw(self, raw_query, params=None, translations=None, using=None):
    105     # 执行原生SQL
    106     models.UserInfo.objects.raw('select * from userinfo')
    107 
    108     # 如果SQL是其他表时,必须将名字设置为当前UserInfo对象的主键列名
    109     models.UserInfo.objects.raw('select id as nid from 其他表')
    110 
    111     # 为原生SQL设置参数
    112     models.UserInfo.objects.raw('select id as nid from userinfo where nid>%s', params=[12,])
    113 
    114     # 将获取的到列名转换为指定列名
    115     name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
    116     Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)
    117 
    118     # 指定数据库
    119     models.UserInfo.objects.raw('select * from userinfo', using="default")
    120 
    121     ################### 原生SQL ###################
    122     from django.db import connection, connections
    123     cursor = connection.cursor()  # cursor = connections['default'].cursor()
    124     cursor.execute("""SELECT * from auth_user where id = %s""", [1])
    125     row = cursor.fetchone() # fetchall()/fetchmany(..)
    126 
    127 
    128 def values(self, *fields):
    129     # 获取每行数据为字典格式
    130 
    131 def values_list(self, *fields, **kwargs):
    132     # 获取每行数据为元祖
    133 
    134 def dates(self, field_name, kind, order='ASC'):
    135     # 根据时间进行某一部分进行去重查找并截取指定内容
    136     # kind只能是:"year"(年), "month"(年-月), "day"(年-月-日)
    137     # order只能是:"ASC"  "DESC"
    138     # 并获取转换后的时间
    139         - year : 年-01-01
    140         - month: 年-月-01
    141         - day  : 年-月-142 
    143     models.DatePlus.objects.dates('ctime','day','DESC')
    144 
    145 def datetimes(self, field_name, kind, order='ASC', tzinfo=None):
    146     # 根据时间进行某一部分进行去重查找并截取指定内容,将时间转换为指定时区时间
    147     # kind只能是 "year", "month", "day", "hour", "minute", "second"
    148     # order只能是:"ASC"  "DESC"
    149     # tzinfo时区对象
    150     models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.UTC)
    151     models.DDD.objects.datetimes('ctime','hour',tzinfo=pytz.timezone('Asia/Shanghai'))
    152 
    153     """
    154     pip3 install pytz
    155     import pytz
    156     pytz.all_timezones
    157     pytz.timezone(‘Asia/Shanghai’)
    158     """
    159 
    160 def none(self):
    161     # 空QuerySet对象
    162 
    163 
    164 ####################################
    165 # METHODS THAT DO DATABASE QUERIES #
    166 ####################################
    167 
    168 def aggregate(self, *args, **kwargs):
    169    # 聚合函数,获取字典类型聚合结果
    170    from django.db.models import Count, Avg, Max, Min, Sum
    171    result = models.UserInfo.objects.aggregate(k=Count('u_id', distinct=True), n=Count('nid'))
    172    ===> {'k': 3, 'n': 4}
    173 
    174 def count(self):
    175    # 获取个数
    176 
    177 def get(self, *args, **kwargs):
    178    # 获取单个对象
    179 
    180 def create(self, **kwargs):
    181    # 创建对象
    182 
    183 def bulk_create(self, objs, batch_size=None):
    184     # 批量插入
    185     # batch_size表示一次插入的个数
    186     objs = [
    187         models.DDD(name='r11'),
    188         models.DDD(name='r22')
    189     ]
    190     models.DDD.objects.bulk_create(objs, 10)
    191 
    192 def get_or_create(self, defaults=None, **kwargs):
    193     # 如果存在,则获取,否则,创建
    194     # defaults 指定创建时,其他字段的值
    195     obj, created = models.UserInfo.objects.get_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 2})
    196 
    197 def update_or_create(self, defaults=None, **kwargs):
    198     # 如果存在,则更新,否则,创建
    199     # defaults 指定创建时或更新时的其他字段
    200     obj, created = models.UserInfo.objects.update_or_create(username='root1', defaults={'email': '1111111','u_id': 2, 't_id': 1})
    201 
    202 def first(self):
    203    # 获取第一个
    204 
    205 def last(self):
    206    # 获取最后一个
    207 
    208 def in_bulk(self, id_list=None):
    209    # 根据主键ID进行查找
    210    id_list = [11,21,31]
    211    models.DDD.objects.in_bulk(id_list)
    212 
    213 def delete(self):
    214    # 删除
    215 
    216 def update(self, **kwargs):
    217     # 更新
    218 
    219 def exists(self):
    220    # 是否有结果
    源码方法中参数分析及举例
     1     # select_related:主动做连表 参数可以为多个外键字段名字  第一次连表直接数据拿出来减少发sql语句请求
     2     q = models.UserInfo.objects.all().select_related('ut')
     3     for row in q:
     4         print(row.username, row.ut.title)
     5     # 外键好处:1.约束2.硬盘占用空间小  但是查询速度要慢点  但是数据量特别大一般不做外键操作
     6 
     7     # prefetch_related:不做连表,增加查询次数
     8     # 两次查询都是单表查询
     9     # 第一次查:select * from userinfo
    10     # 假如公司用户有100个,供选择的用户类型有10种,本公司只有2种用户
    11     # 第二次查:django内部:先拿到用户表中ut_id字段进行去重处理ut_id=[2,4]
    12     # select * from usertype where id in [2,4]
    13     q = models.UserInfo.objects.all().prefetch_related('ut')
    14     for row in q:
    15         print(row.id, row.ut.title)
    性能相关操作  

    在基本操作中filter(age__isnull=True)

    如果用户提交过来的字段比较多
    增加:
    dic = {'name':'xxx','age':18.......}
    create(**dic)
    更新:
    filter(id=1).update(**dic)
    查询: 一大堆条件
    filter(**{'id':1, 'name':'sb'})

    django中models字段

      1 AutoField(Field)
      2         - int自增列,必须填入参数 primary_key=True
      3 
      4     BigAutoField(AutoField)
      5         - bigint自增列,必须填入参数 primary_key=True
      6 
      7         注:当model中如果没有自增列,则自动会创建一个列名为id的列
      8         from django.db import models
      9 
     10         class UserInfo(models.Model):
     11             # 自动创建一个列名为id的且为自增的整数列
     12             username = models.CharField(max_length=32)
     13 
     14         class Group(models.Model):
     15             # 自定义自增列
     16             nid = models.AutoField(primary_key=True)
     17             name = models.CharField(max_length=32)
     18 
     19     SmallIntegerField(IntegerField):
     20         - 小整数 -32768 ~ 32767
     21 
     22     PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
     23         - 正小整数 0 ~ 32767
     24     IntegerField(Field)
     25         - 整数列(有符号的) -2147483648 ~ 2147483647
     26 
     27     PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)
     28         - 正整数 0 ~ 2147483647
     29 
     30     BigIntegerField(IntegerField):
     31         - 长整型(有符号的) -9223372036854775808 ~ 9223372036854775807
     32 
     33     BooleanField(Field)
     34         - 布尔值类型
     35 
     36     NullBooleanField(Field):
     37         - 可以为空的布尔值
     38 
     39     CharField(Field)
     40         - 字符类型
     41         - 必须提供max_length参数, max_length表示字符长度
     42 
     43     TextField(Field)
     44         - 文本类型
     45 
     46     EmailField(CharField):
     47         - 字符串类型,Django Admin以及ModelForm中提供验证机制
     48 
     49     IPAddressField(Field)
     50         - 字符串类型,Django Admin以及ModelForm中提供验证 IPV4 机制
     51 
     52     GenericIPAddressField(Field)
     53         - 字符串类型,Django Admin以及ModelForm中提供验证 Ipv4和Ipv6
     54         - 参数:
     55             protocol,用于指定Ipv4或Ipv6, 'both',"ipv4","ipv6"
     56             unpack_ipv4, 如果指定为True,则输入::ffff:192.0.2.1时候,可解析为192.0.2.1,开启刺功能,需要protocol="both"
     57 
     58     URLField(CharField)
     59         - 字符串类型,Django Admin以及ModelForm中提供验证 URL
     60 
     61     SlugField(CharField)
     62         - 字符串类型,Django Admin以及ModelForm中提供验证支持 字母、数字、下划线、连接符(减号)
     63 
     64     CommaSeparatedIntegerField(CharField)
     65         - 字符串类型,格式必须为逗号分割的数字
     66 
     67     UUIDField(Field)
     68         - 字符串类型,Django Admin以及ModelForm中提供对UUID格式的验证
     69 
     70     FilePathField(Field)
     71         - 字符串,Django Admin以及ModelForm中提供读取文件夹下文件的功能
     72         - 参数:
     73                 path,                      文件夹路径
     74                 match=None,                正则匹配
     75                 recursive=False,           递归下面的文件夹
     76                 allow_files=True,          允许文件
     77                 allow_folders=False,       允许文件夹
     78 
     79     FileField(Field)
     80         - 字符串,路径保存在数据库,文件上传到指定目录
     81         - 参数:
     82             upload_to = ""      上传文件的保存路径
     83             storage = None      存储组件,默认django.core.files.storage.FileSystemStorage
     84 
     85     ImageField(FileField)
     86         - 字符串,路径保存在数据库,文件上传到指定目录
     87         - 参数:
     88             upload_to = ""      上传文件的保存路径
     89             storage = None      存储组件,默认django.core.files.storage.FileSystemStorage
     90             width_field=None,   上传图片的高度保存的数据库字段名(字符串)
     91             height_field=None   上传图片的宽度保存的数据库字段名(字符串)
     92 
     93     DateTimeField(DateField)
     94         - 日期+时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]
     95 
     96     DateField(DateTimeCheckMixin, Field)
     97         - 日期格式      YYYY-MM-DD
     98 
     99     TimeField(DateTimeCheckMixin, Field)
    100         - 时间格式      HH:MM[:ss[.uuuuuu]]
    101 
    102     DurationField(Field)
    103         - 长整数,时间间隔,数据库中按照bigint存储,ORM中获取的值为datetime.timedelta类型
    104 
    105     FloatField(Field)
    106         - 浮点型
    107 
    108     DecimalField(Field)
    109         - 10进制小数
    110         - 参数:
    111             max_digits,小数总长度
    112             decimal_places,小数位长度
    113 
    114     BinaryField(Field)
    115         - 二进制类型
    字段类型
     1 class UnsignedIntegerField(models.IntegerField):
     2     def db_type(self, connection):
     3         return 'integer UNSIGNED'
     4 
     5 PS: 返回值为字段在数据库中的属性,Django字段默认的值为:
     6     'AutoField': 'integer AUTO_INCREMENT',
     7     'BigAutoField': 'bigint AUTO_INCREMENT',
     8     'BinaryField': 'longblob',
     9     'BooleanField': 'bool',
    10     'CharField': 'varchar(%(max_length)s)',
    11     'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
    12     'DateField': 'date',
    13     'DateTimeField': 'datetime',
    14     'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
    15     'DurationField': 'bigint',
    16     'FileField': 'varchar(%(max_length)s)',
    17     'FilePathField': 'varchar(%(max_length)s)',
    18     'FloatField': 'double precision',
    19     'IntegerField': 'integer',
    20     'BigIntegerField': 'bigint',
    21     'IPAddressField': 'char(15)',
    22     'GenericIPAddressField': 'char(39)',
    23     'NullBooleanField': 'bool',
    24     'OneToOneField': 'integer',
    25     'PositiveIntegerField': 'integer UNSIGNED',
    26     'PositiveSmallIntegerField': 'smallint UNSIGNED',
    27     'SlugField': 'varchar(%(max_length)s)',
    28     'SmallIntegerField': 'smallint',
    29     'TextField': 'longtext',
    30     'TimeField': 'time',
    31     'UUIDField': 'char(32)',
    自定义无符号整数字段
     1 1.触发Model中的验证和错误提示有两种方式:
     2         a. Django Admin中的错误信息会优先根据Admiin内部的ModelForm错误信息提示,如果都成功,才来检查Model的字段并显示指定错误信息
     3         b. 使用ModelForm
     4         c. 调用Model对象的 clean_fields 方法,如:
     5             # models.py
     6             class UserInfo(models.Model):
     7                 nid = models.AutoField(primary_key=True)
     8                 username = models.CharField(max_length=32)
     9 
    10                 email = models.EmailField(error_messages={'invalid': '格式错了.'})
    11 
    12             # views.py
    13             def index(request):
    14                 obj = models.UserInfo(username='11234', email='uu')
    15                 try:
    16                     print(obj.clean_fields())
    17                 except Exception as e:
    18                     print(e)
    19                 return HttpResponse('ok')
    20 
    21            # Model的clean方法是一个钩子,可用于定制操作,如:上述的异常处理。
    22 
    23     2.Admin中修改错误提示
    24         # admin.py
    25         from django.contrib import admin
    26         from model_club import models
    27         from django import forms
    28 
    29 
    30         class UserInfoForm(forms.ModelForm):
    31             age = forms.IntegerField(initial=1, error_messages={'required': '请输入数值.', 'invalid': '年龄必须为数值.'})
    32 
    33             class Meta:
    34                 model = models.UserInfo
    35                 # fields = ('username',)
    36                 fields = "__all__"
    37                 exclude = ['title']
    38                 labels = { 'name':'Writer', }
    39                 help_texts = {'name':'some useful help text.',}
    40                 error_messages={ 'name':{'max_length':"this writer name is too long"} }
    41                 widgets={'name':Textarea(attrs={'cols':80,'rows':20})}
    42 
    43         class UserInfoAdmin(admin.ModelAdmin):
    44             form = UserInfoForm
    45 
    46         admin.site.register(models.UserInfo, UserInfoAdmin)
    47 
    48 注意事项
    注意事项

    字段参数

     1 null                数据库中字段是否可以为空
     2     db_column           数据库中字段的列名
     3     default             数据库中字段的默认值
     4     primary_key         数据库中字段是否为主键
     5     db_index            数据库中字段是否可以建立索引
     6     unique              数据库中字段是否可以建立唯一索引
     7     unique_for_date     数据库中字段【日期】部分是否可以建立唯一索引
     8     unique_for_month    数据库中字段【月】部分是否可以建立唯一索引
     9     unique_for_year     数据库中字段【年】部分是否可以建立唯一索引
    10 
    11     verbose_name        Admin中显示的字段名称
    12     blank               Admin中是否允许用户输入为空
    13     editable            Admin中是否可以编辑
    14     help_text           Admin中该字段的提示信息
    15     choices             Admin中显示选择框的内容,用不变动的数据放在内存中从而避免跨表操作
    16                         如:gf = models.IntegerField(choices=[(0, '何穗'),(1, '大表姐'),],default=1)
    17 
    18     error_messages      自定义错误信息(字典类型),从而定制想要显示的错误信息;
    19                         字典健:null, blank, invalid, invalid_choice, unique, and unique_for_date
    20                         如:{'null': "不能为空.", 'invalid': '格式错误'}
    21 
    22     validators          自定义错误验证(列表类型),从而定制想要的验证规则
    23                         from django.core.validators import RegexValidator
    24                         from django.core.validators import EmailValidator,URLValidator,DecimalValidator,
    25                         MaxLengthValidator,MinLengthValidator,MaxValueValidator,MinValueValidator
    26                         如:
    27                             test = models.CharField(
    28                                 max_length=32,
    29                                 error_messages={
    30                                     'c1': '优先错信息1',
    31                                     'c2': '优先错信息2',
    32                                     'c3': '优先错信息3',
    33                                 },
    34                                 validators=[
    35                                     RegexValidator(regex='root_d+', message='错误了', code='c1'),
    36                                     RegexValidator(regex='root_112233d+', message='又错误了', code='c2'),
    37                                     EmailValidator(message='又错误了', code='c3'), ]
    38                             )
    字段的参数归总 

    元信息

     1 class UserInfo(models.Model):
     2         nid = models.AutoField(primary_key=True)
     3         username = models.CharField(max_length=32)
     4         class Meta:
     5             # 数据库中生成的表名称 默认 app名称 + 下划线 + 类名
     6             db_table = "table_name"
     7 
     8             # 联合索引
     9             index_together = [
    10                 ("pub_date", "deadline"),
    11             ]
    12 
    13             # 联合唯一索引
    14             unique_together = (("driver", "restaurant"),)
    15 
    16             # admin中显示的表名称
    17             verbose_name
    18 
    19             # verbose_name加s
    20             verbose_name_plural
    信息 

    多表字段的参数

      1 ForeignKey(ForeignObject) # ForeignObject(RelatedField)
      2         to,                         # 要进行关联的表名
      3         to_field=None,              # 要关联的表中的字段名称
      4         on_delete=None,             # 当删除关联表中的数据时,当前表与其关联的行的行为
      5                                         - models.CASCADE,删除关联数据,与之关联也删除
      6                                         - models.DO_NOTHING,删除关联数据,引发错误IntegrityError
      7                                         - models.PROTECT,删除关联数据,引发错误ProtectedError
      8                                         - models.SET_NULL,删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空)
      9                                         - models.SET_DEFAULT,删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值)
     10                                         - models.SET,删除关联数据,
     11                                                       a. 与之关联的值设置为指定值,设置:models.SET(值)
     12                                                       b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)
     13 
     14                                                         def func():
     15                                                             return 10
     16 
     17                                                         class MyModel(models.Model):
     18                                                             user = models.ForeignKey(
     19                                                                 to="User",
     20                                                                 to_field="id"
     21                                                                 on_delete=models.SET(func),)
     22         related_name=None,          # 反向操作时,使用的字段名,用于代替 【表名_set】 如: obj.表名_set.all()
     23         related_query_name=None,    # 反向操作时,使用的连接前缀,用于替换【表名】     如: models.UserGroup.objects.filter(表名__字段名=1).values('表名__字段名')
     24         limit_choices_to=None,      # 在Admin或ModelForm中显示关联数据时,提供的条件:
     25                                     # 如:
     26                                             - limit_choices_to={'nid__gt': 5}
     27                                             - limit_choices_to=lambda : {'nid__gt': 5}
     28 
     29                                             from django.db.models import Q
     30                                             - limit_choices_to=Q(nid__gt=10)
     31                                             - limit_choices_to=Q(nid=8) | Q(nid__gt=10)
     32                                             - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')
     33         db_constraint=True          # 是否在数据库中创建外键约束
     34         parent_link=False           # 在Admin中是否显示关联数据
     35 
     36 
     37     OneToOneField(ForeignKey)
     38         to,                         # 要进行关联的表名
     39         to_field=None               # 要关联的表中的字段名称
     40         on_delete=None,             # 当删除关联表中的数据时,当前表与其关联的行的行为
     41 
     42                                     ###### 对于一对一 ######
     43                                     # 1. 一对一其实就是 一对多 + 唯一索引
     44                                     # 2.当两个类之间有继承关系时,默认会创建一个一对一字段
     45                                     # 如下会在A表中额外增加一个c_ptr_id列且唯一:
     46                                             class C(models.Model):
     47                                                 nid = models.AutoField(primary_key=True)
     48                                                 part = models.CharField(max_length=12)
     49 
     50                                             class A(C):
     51                                                 id = models.AutoField(primary_key=True)
     52                                                 code = models.CharField(max_length=1)
     53 
     54     ManyToManyField(RelatedField)
     55         to,                         # 要进行关联的表名
     56         related_name=None,          # 反向操作时,使用的字段名,用于代替 【表名_set】 如: obj.表名_set.all()
     57         related_query_name=None,    # 反向操作时,使用的连接前缀,用于替换【表名】     如: models.UserGroup.objects.filter(表名__字段名=1).values('表名__字段名')
     58         limit_choices_to=None,      # 在Admin或ModelForm中显示关联数据时,提供的条件:
     59                                     # 如:
     60                                             - limit_choices_to={'nid__gt': 5}
     61                                             - limit_choices_to=lambda : {'nid__gt': 5}
     62 
     63                                             from django.db.models import Q
     64                                             - limit_choices_to=Q(nid__gt=10)
     65                                             - limit_choices_to=Q(nid=8) | Q(nid__gt=10)
     66                                             - limit_choices_to=lambda : Q(Q(nid=8) | Q(nid__gt=10)) & Q(caption='root')
     67         symmetrical=None,           # 仅用于多对多自关联时,symmetrical用于指定内部是否创建反向操作的字段
     68                                     # 做如下操作时,不同的symmetrical会有不同的可选字段
     69                                         models.BB.objects.filter(...)
     70 
     71                                         # 可选字段有:code, id, m1
     72                                             class BB(models.Model):
     73 
     74                                             code = models.CharField(max_length=12)
     75                                             m1 = models.ManyToManyField('self',symmetrical=True)
     76 
     77                                         # 可选字段有: bb, code, id, m1
     78                                             class BB(models.Model):
     79 
     80                                             code = models.CharField(max_length=12)
     81                                             m1 = models.ManyToManyField('self',symmetrical=False)
     82 
     83         through=None,               # 自定义第三张表时,使用字段用于指定关系表
     84         through_fields=None,        # 自定义第三张表时,使用字段用于指定关系表中那些字段做多对多关系表
     85                                         from django.db import models
     86 
     87                                         class Person(models.Model):
     88                                             name = models.CharField(max_length=50)
     89 
     90                                         class Group(models.Model):
     91                                             name = models.CharField(max_length=128)
     92                                             members = models.ManyToManyField(
     93                                                 Person,
     94                                                 through='Membership',
     95                                                 through_fields=('group', 'person'),
     96                                             )
     97 
     98                                         class Membership(models.Model):
     99                                             group = models.ForeignKey(Group, on_delete=models.CASCADE)
    100                                             person = models.ForeignKey(Person, on_delete=models.CASCADE)
    101                                             inviter = models.ForeignKey(
    102                                                 Person,
    103                                                 on_delete=models.CASCADE,
    104                                                 related_name="membership_invites",
    105                                             )
    106                                             invite_reason = models.CharField(max_length=64)
    107         db_constraint=True,         # 是否在数据库中创建外键约束
    108         db_table=None,              # 默认创建第三张表时,数据库中表的名称
    多表字段参数

    多对多操作

    models.py

     1 from django.db import models
     2 
     3 
     4 class Boy(models.Model):
     5     name = models.CharField(max_length=32)
     6     # m = models.ManyToManyField('Girl')
     7     m = models.ManyToManyField('Girl', through='Love', through_fields=('b', 'g', ))
     8     # 报的错ValueError: Cannot alter field app01.Boy.m into app01.Boy.m - they are not compatible types (you cannot alter to or 
     9     # from M2M fields, or add or remove through= on M2M fields) 为何不能生成表呢?因为在这里如果在Love表中有其它字段,就不能操作了嘛所以说不能add remove set但是可以all进行查询、也可以clear
    10     # 内置ManyToMany字段只能生成三列id/b_id/g_id 如果想增加其它字段列只有自己写第三张表
    11     # 我习惯自定义第三张表这样灵活一些,第三张表就可以定义其它的字段
    12     # 1.创建外键表2.看需求简单就用ManyToManyField字段
    13 
    14 
    15 class Girl(models.Model):
    16     nick = models.CharField(max_length=32)
    17     # m = models.ManyToManyField('Boy')
    18 
    19 
    20 class Love(models.Model):
    21     b = models.ForeignKey('Boy', on_delete=models.CASCADE)
    22     g = models.ForeignKey('Girl', on_delete=models.CASCADE)
    23 
    24     class Meta:
    25         unique_together = [
    26             ('b', 'g'),
    27         ]
     1 """modelsm2m URL Configuration
     2 
     3 The `urlpatterns` list routes URLs to views. For more information please see:
     4     https://docs.djangoproject.com/en/2.1/topics/http/urls/
     5 Examples:
     6 Function views
     7     1. Add an import:  from my_app import views
     8     2. Add a URL to urlpatterns:  path('', views.home, name='home')
     9 Class-based views
    10     1. Add an import:  from other_app.views import Home
    11     2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
    12 Including another URLconf
    13     1. Import the include() function: from django.urls import include, path
    14     2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
    15 """
    16 from django.contrib import admin
    17 from django.urls import path
    18 from app01 import views
    19 
    20 urlpatterns = [
    21     path('admin/', admin.site.urls),
    22     path('index/', views.index),
    23 ]
     1 from django.shortcuts import render, HttpResponse
     2 from app01 import models
     3 
     4 
     5 def index(request):
     6     # 多对多
     7     # objs = [
     8     #     models.Boy(name='大傻'),
     9     #     models.Boy(name='和苏'),
    10     #     models.Boy(name='旭哥'),
    11     #     models.Boy(name='爆音哥'),
    12     #     models.Boy(name='Hot dog'),
    13     # ]
    14     # models.Boy.objects.bulk_create(objs, 5)
    15     # objs = [
    16     #     models.Girl(nick='紫棋'),
    17     #     models.Girl(nick='open'),
    18     #     models.Girl(nick='翠花'),
    19     #     models.Girl(nick='呆妹儿'),
    20     #     models.Girl(nick='提莫'),
    21     # ]
    22     # models.Girl.objects.bulk_create(objs, 5)
    23 
    24     # models.Love.objects.create(b_id=2, g_id=2)
    25     # models.Love.objects.create(b_id=2, g_id=4)
    26     # models.Love.objects.create(b_id=5, g_id=1)
    27     # models.Love.objects.create(b_id=5, g_id=5)
    28 
    29     # 需求查与和苏有关的菇娘
    30     # 1反向
    31     # obj = models.Boy.objects.filter(name='和苏').first()
    32     # love_list = obj.love_set.all()
    33     # for row in love_list:
    34     #     print(row.g.nick)
    35 
    36     # 2正向
    37     # love_list = models.Love.objects.filter(b__name='和苏')
    38     # for row in love_list:
    39     #     print(row.g.nick)  # 上述两种方式在循环时跨表
    40 
    41     # 3正 直接连表 values  values_list
    42     # love_list = models.Love.objects.filter(b__name='和苏').values('g__nick')
    43     # for row in love_list:
    44     #     print(row['g__nick'])
    45 
    46     # 4.select_related
    47     # love_list = models.Love.objects.filter(b__name='和苏').select_related('g')
    48     # for obj in love_list:
    49     #     print(obj.g.nick)
    50 
    51     # 3和4 两种方式好点
    52 
    53     # m = models.ManyToManyField('Girl')
    54     # 正向
    55     # obj = models.Boy.objects.filter(name='Hot dog').first()
    56     # print(obj.id, obj.name)
    57     # 增加add
    58     # obj.m.add(1)
    59     # obj.m.add(2, 3)
    60     # obj.m.add(*[4, ])
    61 
    62     # 删除remove
    63     # obj.m.remove(1)
    64     # obj.m.remove(2, 3)
    65     # obj.m.remove(*[4, ])
    66 
    67     # 重置set  参数要被迭代
    68     # obj.m.set([1, ])
    69 
    70     # 获取
    71     # q = obj.m.all()
    72     # print(q)
    73     # <QuerySet [<Girl: Girl object (1)>]>
    74     # obj = models.Boy.objects.filter(name='Hot dog').first()
    75     # girl_list = obj.m.all()
    76     # girl_list = obj.m.filter(nick='open') 又进行一次筛选
    77 
    78     # 单身一辈子
    79     # obj = models.Boy.objects.filter(name='Hot dog').first()
    80     # obj.m.clear()
    81 
    82 
    83     # 反向
    84     obj = models.Girl.objects.filter(nick='紫棋').first()
    85     v = obj.boy_set.all()
    86     print(v)
    87     # <QuerySet [<Boy: Boy object (5)>, <Boy: Boy object (4)>]>
    88     # v = obj.boy_set.add()
    89     # v = obj.boy_set.remove()
    90     # v = obj.boy_set.set()
    91     # v = obj.boy_set.clear()
    92 
    93     return HttpResponse('.......')

     自关联注意:

    不指名别名django在外键查找不知道通过什么字段找,就会报错

    其它

    1 import pymysql
    2     from django.db import connection, connections
    3  
    4     connection.connect()
    5     conn = connection.connection
    6     cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    7     cursor.execute("""SELECT * from app01_userinfo""")
    8     row = cursor.fetchone()
    9     connection.close()
    Django原生SQL获取cursor字典
     1 # 数字自增
     2     from django.db.models import F
     3     models.UserInfo.objects.update(num=F('num') + 1)
     4 
     5     # 字符串更新
     6     from django.db.models.functions import Concat
     7     from django.db.models import Value
     8 
     9     models.UserInfo.objects.update(name=Concat('name', 'pwd'))
    10     models.UserInfo.objects.update(name=Concat('name', Value('666')))
    数字自增、字符串更新
     1 # ########### 基础函数 ###########
     2 
     3     # 1. Concat,用于做类型转换
     4     # v = models.UserInfo.objects.annotate(c=Cast('pwd', FloatField()))
     5 
     6     # 2. Coalesce,从前向后,查询第一个不为空的值
     7     # v = models.UserInfo.objects.annotate(c=Coalesce('name', 'pwd'))
     8     # v = models.UserInfo.objects.annotate(c=Coalesce(Value('666'),'name', 'pwd'))
     9 
    10     # 3. Concat,拼接
    11     # models.UserInfo.objects.update(name=Concat('name', 'pwd'))
    12     # models.UserInfo.objects.update(name=Concat('name', Value('666')))
    13     # models.UserInfo.objects.update(name=Concat('name', Value('666'),Value('999')))
    14 
    15     # 4.ConcatPair,拼接(仅两个参数)
    16     # v = models.UserInfo.objects.annotate(c=ConcatPair('name', 'pwd'))
    17     # v = models.UserInfo.objects.annotate(c=ConcatPair('name', Value('666')))
    18 
    19     # 5.Greatest,获取比较大的值;least 获取比较小的值;
    20     # v = models.UserInfo.objects.annotate(c=Greatest('id', 'pwd',output_field=FloatField()))
    21 
    22     # 6.Length,获取长度
    23     # v = models.UserInfo.objects.annotate(c=Length('name'))
    24 
    25     # 7. Lower,Upper,变大小写
    26     # v = models.UserInfo.objects.annotate(c=Lower('name'))
    27     # v = models.UserInfo.objects.annotate(c=Upper('name'))
    28 
    29     # 8. Now,获取当前时间
    30     # v = models.UserInfo.objects.annotate(c=Now())
    31 
    32     # 9. substr,子序列
    33     # v = models.UserInfo.objects.annotate(c=Substr('name',1,2))
    34 
    35     # ########### 时间类函数 ###########
    36     # 1. 时间截取,不保留其他:Extract, ExtractDay, ExtractHour, ExtractMinute, ExtractMonth,ExtractSecond, ExtractWeekDay, ExtractYear,
    37     # v = models.UserInfo.objects.annotate(c=functions.ExtractYear('ctime'))
    38     # v = models.UserInfo.objects.annotate(c=functions.ExtractMonth('ctime'))
    39     # v = models.UserInfo.objects.annotate(c=functions.ExtractDay('ctime'))
    40     #
    41     # v = models.UserInfo.objects.annotate(c=functions.Extract('ctime', 'year'))
    42     # v = models.UserInfo.objects.annotate(c=functions.Extract('ctime', 'month'))
    43     # v = models.UserInfo.objects.annotate(c=functions.Extract('ctime', 'year_month'))
    44     """
    45     MICROSECOND
    46     SECOND
    47     MINUTE
    48     HOUR
    49     DAY
    50     WEEK
    51     MONTH
    52     QUARTER
    53     YEAR
    54     SECOND_MICROSECOND
    55     MINUTE_MICROSECOND
    56     MINUTE_SECOND
    57     HOUR_MICROSECOND
    58     HOUR_SECOND
    59     HOUR_MINUTE
    60     DAY_MICROSECOND
    61     DAY_SECOND
    62     DAY_MINUTE
    63     DAY_HOUR
    64     YEAR_MONTH
    65     """
    66 
    67     # 2. 时间截图,保留其他:Trunc, TruncDate, TruncDay,TruncHour, TruncMinute, TruncMonth, TruncSecond, TruncYear
    68     # v = models.UserInfo.objects.annotate(c=functions.TruncHour('ctime'))
    69     # v = models.UserInfo.objects.annotate(c=functions.TruncDate('ctime'))
    70     # v = models.UserInfo.objects.annotate(c=functions.Trunc('ctime','year'))
    ORM函数相关
     1 from django.db.models.functions.base import Func
     2     class CustomeFunc(Func):
     3         function = 'DATE_FORMAT'
     4         template = '%(function)s(%(expressions)s,%(format)s)'
     5 
     6         def __init__(self, expression, **extra):
     7             expressions = [expression]
     8             super(CustomeFunc, self).__init__(*expressions, **extra)
     9 
    10     v = models.UserInfo.objects.annotate(c=CustomeFunc('ctime',format="'%%Y-%%m'"))
    ORM自定义函数

     总结:

    查询数据的时候无论怎样,先滤清表与表之间的关系,然后不论正反操作都可以实现(一对多,多对多都可以实现)。

    当然第二个条件时候,性能上的也要进行优化,尽量避免发多次的sql请求,尤其是数量大的情况更应该考虑。

    admin(有些models字段名称专为admin定制的)

             django amdin是django提供的一个后台管理页面,改管理页面提供完善的html和css,使得你在通过Model创建完数据库表之后,就可以对数据进行增删改查,而使用django admin 则需要以下步骤:

    • 创建后台管理员
    • 配置url
    • 注册和配置django admin后台管理页面

    1、创建后台管理员

    python manage.py createsuperuser
    

    2、配置后台管理url

     path('admin/', admin.site.urls),
    

    3、注册和配置django admin 后台管理页面

    a、在admin中执行如下配置

    from django.contrib import admin
      
    from app01 import  models
      
    admin.site.register(models.UserType)
    admin.site.register(models.UserInfo)
    admin.site.register(models.UserGroup)
    admin.site.register(models.Asset)
    

    b、设置数据表名称

    class UserType(models.Model):
        name = models.CharField(max_length=50)
      
        class Meta:
            verbose_name = '用户类型'
            verbose_name_plural = '用户类型'
    

    c、打开表之后,设定默认显示,需要在model中作如下配置

    class UserType(models.Model):
        name = models.CharField(max_length=50)
      
        def __unicode__(self):
            return self.name 
    from django.contrib import admin
      
    from app01 import  models
      
    class UserInfoAdmin(admin.ModelAdmin):
        list_display = ('username', 'password', 'email')
      
      
    admin.site.register(models.UserType)
    admin.site.register(models.UserInfo,UserInfoAdmin)
    admin.site.register(models.UserGroup)
    admin.site.register(models.Asset)
    

    d、为数据表添加搜索功能

    from django.contrib import admin
      
    from app01 import  models
      
    class UserInfoAdmin(admin.ModelAdmin):
        list_display = ('username', 'password', 'email')
        search_fields = ('username', 'email')
      
    admin.site.register(models.UserType)
    admin.site.register(models.UserInfo,UserInfoAdmin)
    admin.site.register(models.UserGroup)
    admin.site.register(models.Asset)
    

    e、添加快速过滤

    from django.contrib import admin
      
    from app01 import  models
      
    class UserInfoAdmin(admin.ModelAdmin):
        list_display = ('username', 'password', 'email')
        search_fields = ('username', 'email')
        list_filter = ('username', 'email')
          
      
      
    admin.site.register(models.UserType)
    admin.site.register(models.UserInfo,UserInfoAdmin)
    admin.site.register(models.UserGroup)
    admin.site.register(models.Asset)
    

    更多:http://docs.30c.org/djangobook2/chapter06/  

      

     

     

      

      

      

      

  • 相关阅读:
    PHP里文件的查找方式及写法
    上传文件
    用ajax对数据进行查看人员信息
    ajax实现分页
    jquery做个日期选择适用于手机端
    PHP用ajia代码写三级联动下拉
    JSON数据的定义
    jquery做一些小的特效
    对jquery操作复选框
    使用 LUT 模拟光照
  • 原文地址:https://www.cnblogs.com/Alexephor/p/11258394.html
Copyright © 2011-2022 走看看