Django Model各種操作 Meta 常用欄位 一對多操作 多對對操作 F Q查詢 聚合函式

心--癮發表於2020-10-28

Model操作

  1. meta源資訊

    class CLS(models.Model):
        username = models.CharField(max_length=32)
    
        class Meta:
            db_table = "table_cls"
    
    
    # Meta源資訊
    class UserInfo(models.Model):
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=32)
        cls = models.ForeignKey(CLS, models.CASCADE)
    
        class Meta:
            # 1 資料庫中生成的表名稱 預設 app名稱 + 下劃線 + 類名
            db_table = "table_name"  # 自己指定建立的表名
            # 2 Django Admin 中顯示的表名稱
            verbose_name = 'user'  # 在Django admin後臺顯示時表名是users
            # 3 verbose_name加s
            verbose_name_plural = 'user'  # 若果這個欄位也是user那麼4中表名才顯示user
            # 4 聯合唯一索引
            unique_together = (("username", "cls"),)
            # 5 聯合索引 (缺點是最左字首,寫SQL語句基於password時不能命中索引,查詢慢)
            # 如:select * from tb where password = ‘xx’ 就無法命中索引
            index_together = [
                ("username", "cls"),
            ]
    
  2. 常用欄位

    class UserGroup(models.Model):
        uid = models.AutoField(primary_key=True)
        name = models.CharField(max_length=32, null=True, blank=True)
        email = models.EmailField(max_length=32)
        text = models.TextField()
        ctime = models.DateTimeField(auto_now_add=True)  # 只有新增時才會更新時間
        uptime = models.DateTimeField(auto_now=True)  # 只要修改就會更新時間
        # ip1 = models.IPAddressField() # 字串型別,Django Admin以及ModelForm中提供驗證 IPV4 機制
        ip2 = models.GenericIPAddressField()  
        # 字串型別,Django Admin以及ModelForm中提供驗證 Ipv4和Ipv6
        active = models.BooleanField(default=True)
        data01 = models.DateTimeField()  
        # 日期+時間格式 YYYY-MM-DDHH:MM[:ss[.uuuuuu]][TZ
        data02 = models.DateField()  # 日期格式   -MMDD
        data03 = models.TimeField()  # 時間格式HH:MM[:ss[.uuuuuu]]
        age = models.PositiveIntegerField()  # 正小整數 0 ~ 32767
        balance = models.SmallIntegerField()  # 小整數 -32768 ~ 32767
        money = models.PositiveIntegerField()  # 正整數 0 ~ 2147483647
        bignum = models.BigIntegerField()  # 長整型(有符號的)-9223372036854775808 ~ 9223372036854775807
        user_type_choices = (
            (1, "超級使用者"),
            (2, "普通使用者"),
            (3, "普普通使用者"),
        )
        user_type_id = models.IntegerField(choices=user_type_choices, default=1)
    
  3. 一對多基本增刪改查

    1. models
      class UserType(models.Model):
          type_name = models.CharField(max_length=64, unique=True)
      
      
      class UserInfo(models.Model):
          name = models.CharField(max_length=64, unique=True)
          ut = models.ForeignKey(to='UserType', on_delete=models.CASCADE)
      
    2. views
      def orm(request):
          # 1 建立
          # 建立資料方法一
          # models.UserInfo.objects.create(name='root', ut_id=2)
      
          # 建立資料方法二
          # obj = models.UserInfo(name='root2', ut_id=2)
          # obj.save()
      
          # 建立資料庫方法三(傳入字典必須在字典前加兩個星號)
          # dic = {'name': 'root3', 'ut_id': 2}
          # models.UserInfo.objects.create(**dic)
      
          # 2 刪除
          # models.UserInfo.objects.all().delete() # 刪除所有
          # models.UserInfo.objects.filter(name='root').delete()  # 刪除指定
      
          # 3 更新
          # models.UserInfo.objects.all().update(ut_id=1)
          # models.UserInfo.objects.filter(name='zhangsan').update(ut_id=4)
      
          # 4.查詢
          # 4.1 正向查詢 user_obj.ut.type_name
          print(models.UserInfo.objects.get(name='root').ut.type_name)  # root屬於誰
          print(models.UserInfo.objects.filter(ut__type_name='zs'))  #外來鍵名字
          # # 4.2 反向查詢 type_obj.userinfo_set.all()
          print(models.UserType.objects.get(type_name='ls').userinfo_set.all())  #外來鍵名字 獲取所有
          print(models.UserType.objects.get(type_name='ls').userinfo_set.filter(name='root'))  # 外來鍵名下的root
          return HttpResponse('orm')
      
    3. 資料庫結構
      usertype

      id type_name
      2 ls
      3 oo
      1 zs

      userinfo

      id name ut_id
      5 root2 1
      6 root3 2
      11 root 2

    4. 查詢返回

      ls
      <QuerySet [<UserInfo: UserInfo object (5)>]>
      <QuerySet [<UserInfo: UserInfo object (6)>, <UserInfo: UserInfo object (11)>]>
      <QuerySet [<UserInfo: UserInfo object (11)>]>

  4. 一對多查詢更多操作

    1. mdoels
      from django.db import models
      
      # Create your models here.
      from django.db import models
      
      # 2.3 一對多ForeignKey可選引數
      """
      1、to, # 要進行關聯的表名
      2、to_field=None, # 要關聯的表中的欄位名稱
      3、on_delete=None, # 當刪除關聯表中的資料時,當前表與其關
      聯的行的行為
      - models.CASCADE # ,刪除關聯資料,與之關聯也刪除
      - models.DO_NOTHING # ,刪除關聯資料,引發錯誤
      IntegrityError
      - models.PROTECT # ,刪除關聯資料,引發錯誤
      ProtectedError
      - models.SET_NULL # ,刪除關聯資料,與之關聯的值設定為
      null(前提FK欄位需要設定為可空)
      - models.SET_DEFAULT # ,刪除關聯資料,與之關聯的值設定為默
      認值(前提FK欄位需要設定預設值)
      - models.SET # ,刪除關聯資料,
      4、related_name=None, # 反向操作時,使用的欄位名,用於代替
      【表名_set】 如: obj.表名_set.all()
      # 在做自關聯時必須指定此欄位,防止查詢
      衝突
      5、delated_query_name=None, # 反向操作時,使用的連線字首,用於替換
      【表名】
      # 如:
      models.UserGroup.objects.filter(表名__欄位名=1).values('表名__欄位名')
      
      """
      
      
      class UserType(models.Model):
          user_type_name = models.CharField(max_length=32)
      
          def __str__(self):
              return self.user_type_name  # 只有加上這個,Django admin才會顯示錶名
      
      
      class User(models.Model):
          username = models.CharField(max_length=32)
          pwd = models.CharField(max_length=64)
          ut = models.ForeignKey(
              to='UserType',
              to_field='id',
              # 1、反向操作時,使用的連線字首,用於替換【表名】
              # 如: models.UserGroup.objects.filter(a__欄位名=1).values('a__欄位名')
              related_query_name='a',
              # 2、反向操作時,使用的欄位名,用於代替 【表名_set】 如: obj.b_set.all()
              # 使用時查詢報錯
              # related_name='b',
              on_delete=models.CASCADE
          )
      
    2. views
      from django.shortcuts import HttpResponse
      from . import models
      
      # 一對多查詢更多操作
      
      def orm2(request):
          # 1 正向查詢
          # 1.1 正向查詢user表使用者名稱
          print(models.User.objects.get(username='zhangsan').pwd)  # 查詢到的  .獲取
          # 1.2 正向跨表查詢使用者型別
          print(models.User.objects.get(username='zhangsan').ut.user_type_name)  # 獲取查詢到的外來鍵名字
          # 1.3 雙下劃線正向跨表正向查詢
          print(models.User.objects.all().values('ut__user_type_name', 'username'))  # 查詢外來鍵名稱下 包含的名稱
          # 2 反向查詢
          # 2.1:【表名_set】,反向查詢user表中使用者型別為student 的所有使用者
          print(models.UserType.objects.get(user_type_name='student').user_set.all())  # 獲取student外來鍵下所有的user
          # [<User: lisi>, <User: wangwu>]
          # 2.2:【a__欄位名】反向查詢user表中張三在UserType表中的型別:([<UserType:teacher >])
          print(models.UserType.objects.filter(a__username='zhangsan'))  # 獲取張三下的外來鍵
          # student
          # 這裡的a是user表的ForeignKey欄位的引數:related_query_name='a'
          # 2.3: 雙下劃線跨表反向查詢
          print(models.UserType.objects.all().values('a__username', 'user_type_name')  # 通過名字獲取外來鍵名
                )
          # 3 自動建立User表和UserType表中的資料
          '''
          username = [{'username':'zhangsan','pwd':'123','ut_id':'1'},
          {'username':'lisi','pwd':'123','ut_id':'1'},
          {'username':'wangwu','pwd':'123','ut_id':'1'},]
          user_type = [{'user_type_name':'student'},{'user_type_name':'teacher'},]
          for type_dic in user_type:Z
          models.UserType.objects.create(**type_dic)
          for user_dic in username:
          models.User.objects.create(**user_dic)
          '''
          return HttpResponse('orm')
      
      
      
    3. 資料庫結構、

      user

      id username pwd ut_id
      1 qwe 123 1
      2 asd 123 1
      3 rty 123 2
      4 zhangsan 123 1

      usertype

      id user_type_name
      1 tea
      2 student
      3 wangwu

    4. 查詢返回

      123
      tea
      <QuerySet [{‘ut__user_type_name’: ‘tea’, ‘username’: ‘qwe’}, {‘ut__user_type_name’: ‘tea’, ‘username’: ‘asd’}, {‘ut__user_type_name’: ‘student’, ‘username’: ‘rty’}, {‘ut__user_type_name’: ‘tea’, ‘username’: ‘zhangsan’}]>
      <QuerySet [<User: User object (3)>]>
      <QuerySet [<UserType: tea>]>
      <QuerySet [{‘a__username’: ‘qwe’, ‘user_type_name’: ‘tea’}, {‘a__username’: ‘asd’, ‘user_type_name’: ‘tea’}, {‘a__username’: ‘rty’, ‘user_type_name’: ‘student’}, {‘a__username’: ‘zhangsan’, ‘user_type_name’: ‘tea’}, {‘a__username’: None, ‘user_type_name’: ‘wangwu’}]>

  5. 一對多使用values和values_list結合雙下劃線跨表查詢

    1. mdoels
      class UserType(models.Model):
          user_type_name = models.CharField(max_length=32)
      
          def __str__(self):
              return self.user_type_name  # 只有加上這個,Django admin才會顯示錶名
      
      
      class User(models.Model):
          username = models.CharField(max_length=32)
          pwd = models.CharField(max_length=64)
          ut = models.ForeignKey(
              to='UserType',
              to_field='id',
              # 1、反向操作時,使用的連線字首,用於替換【表名】
              # 如: models.UserGroup.objects.filter(a__欄位名=1).values('a__欄位名')
              related_query_name='a',
              # 2、反向操作時,使用的欄位名,用於代替 【表名_set】 如: obj.b_set.all()
              # 使用時查詢報錯
              # related_name='b',
              on_delete=models.CASCADE
          )
      
    2. views
      # 2.3 一對多使用values和values_list結合雙下劃線跨表查詢
      def orm3(request):
          # 第一種:values-----獲取的內部是字典 拿固定列數
          # 1.1 正向查詢: 使用ForeignKey欄位名ut結合雙下劃線查詢
          print(models.User.objects.filter(username='zhangsan').values('username', 'ut__user_type_name'))   #獲取名稱和外來鍵名稱
          # 1.2 正向查詢: 使用ForeignKey的related_query_name='a',的欄位
          print(models.UserType.objects.all().values('user_type_name', 'a__username'))   #獲取名稱和 外來鍵包含名稱
          # 第二種:values_list-----獲取的是元組 拿固定列數
          # 1.1 正向查詢: 使用ForeignKey欄位名ut結合雙下劃線查詢
          stus = models.User.objects.filter(username='zhangsan').values_list('username', 'ut__user_type_name')  #姓名等於zhangsan的外來鍵名稱
          print(stus)
          # 1.2 反向查詢: 使用ForeignKey的related_query_name='a',的欄位
          utype = models.UserType.objects.all().values_list('user_type_name', 'a__username')   #獲取名稱和 外來鍵包含名稱
          print(utype)
          # 3 自動建立User表和UserType表中的資料
          '''
          username = [{'username':'zhangsan','pwd':'123','ut_id':'1'},
          {'username':'lisi','pwd':'123','ut_id':'1'},
          {'username':'wangwu','pwd':'123','ut_id':'1'},]
          user_type = [{'user_type_name':'student'},{'user_type_name':'teacher'},]
          for type_dic in user_type:
          models.UserType.objects.create(**type_dic)
          for user_dic in username:
          models.User.objects.create(**user_dic)
          
          
          id username   pwd    ut_id
          1  qwe    123    1
          2  asd    123    1
          3  rty    123    2
          4  zhangsan 123   1
          '''
          return HttpResponse('orm')
      
    3. 資料庫結構

      user

      id username pwd ut_id
      1 qwe 123 1
      2 asd 123 1
      3 rty 123 2
      4 zhangsan 123 1

      usertype

      id user_type_name
      1 tea
      2 student
      3 wangwu

    4. 查詢返回

      <QuerySet [{‘user_type_name’: ‘tea’, ‘a__username’: ‘qwe’}, {‘user_type_name’: ‘tea’, ‘a__username’: ‘asd’}, {‘user_type_name’: ‘student’, ‘a__username’: ‘rty’}, {‘user_type_name’: ‘tea’, ‘a__username’: ‘zhangsan’}, {‘user_type_name’: ‘wangwu’, ‘a__username’: None}]>
      <QuerySet [(‘zhangsan’, ‘tea’)]>
      <QuerySet [(‘tea’, ‘qwe’), (‘tea’, ‘asd’), (‘student’, ‘rty’), (‘tea’, ‘zhangsan’), (‘wangwu’, None)]>

  6. ManyToManyField多對多

    1. mdoels
      from django.db import models
      # ManyToManyField
      # Create your models here.
      from django.db import models
      
      
      class UserInfo(models.Model):
          username = models.CharField(max_length=32)
      
          def __str__(self):
              return self.username
      
      
      class UserGroup(models.Model):
          group_name = models.CharField(max_length=64)
          user_info = models.ManyToManyField(to='UserInfo', related_query_name='m2m')
      
          def __str__(self):
              return self.group_name
      
    2. views
      from django.shortcuts import HttpResponse
      from . import models
      
      # 多對多查詢
      def orm4(request):
      
          user_info_obj = models.UserInfo.objects.get(username='zhangsan')
          user_info_objs = models.UserInfo.objects.all()
          group_obj = models.UserGroup.objects.get(group_name='group_python')
          group_objs = models.UserGroup.objects.all()
          # 新增: 正向
          group_obj.user_info.add(user_info_obj)
          group_obj.user_info.add(*user_info_objs)
          # 刪除:正向
          # group_obj.user_info.remove(user_info_obj)
          # group_obj.user_info.remove(*user_info_objs)
          # 新增: 反向
          user_info_obj.usergroup_set.add(group_obj)
          user_info_obj.usergroup_set.add(*group_objs)
          # 刪除:反向
          # user_info_obj.usergroup_set.remove(group_obj)
          # user_info_obj.usergroup_set.remove(*group_objs)
          # 查詢:正向
          print(group_obj.user_info.all())  # 查詢group_python組中所有使用者
          print(group_obj.user_info.all().filter(username='zhangsan'))
          # 查詢:反向
          print(user_info_obj.usergroup_set.all())  # 查詢使用者zhangsan屬於那些組
          print(user_info_obj.usergroup_set.all().filter(group_name='group_python'))
          # 雙下劃線 正向、反向查詢
          # 正向:從使用者組表中查詢zhangsan屬於哪個使用者組:[<UserGroup: group_python>]
          print(models.UserGroup.objects.filter(user_info__username='zhangsan'))
          # 反向:從使用者表中查詢group_python組中有哪些使用者:related_query_name='m2m'
          print(models.UserInfo.objects.filter(m2m__group_name='group_python'))
      
          # 自動建立UserInfo表和UserGroup表中的資料
          '''
          user_list = [{'username':'zhangsan'},
          {'username':'lisi'},
          {'username':'wangwu'},]
          group_list = [{'group_name':'group_python'},
          {'group_name':'group_linux'},
          {'group_name':'group_mysql'},]
          for c in user_list:
          models.UserInfo.objects.create(**c)
          for l in group_list:
          models.UserGroup.objects.create(**l)
          '''
          return HttpResponse('orm')
      
    3. 資料庫結構

      usergroup

      id group_name
      1 group_python
      2 group_linux
      3 group_mysql

      userinfo

      id username
      1 zhangsan
      2 lisi
      3 wangwu

      usergroup_user_info

      id usergroup_id userinfo_id
      33 1 1
      34 1 2
      35 1 3
      36 2 1
      21 2 3
      37 3 1
      23 3 3

    4. 查詢返回

      <QuerySet [{‘user_type_name’: ‘tea’, ‘a__username’: ‘qwe’}, {‘user_type_name’: ‘tea’, ‘a__username’: ‘asd’}, {‘user_type_name’: ‘student’, ‘a__username’: ‘rty’}, {‘user_type_name’: ‘tea’, ‘a__username’: ‘zhangsan’}, {‘user_type_name’: ‘wangwu’, ‘a__username’: None}]>
      <QuerySet [(‘zhangsan’, ‘tea’)]>
      <QuerySet [(‘tea’, ‘qwe’), (‘tea’, ‘asd’), (‘student’, ‘rty’), (‘tea’, ‘zhangsan’), (‘wangwu’, None)]>
      <QuerySet [<UserInfo: zhangsan>, <UserInfo: lisi>, <UserInfo: wangwu>]>
      <QuerySet [<UserInfo: zhangsan>]>
      <QuerySet [<UserGroup: group_python>, <UserGroup: group_linux>, <UserGroup: group_mysql>]>
      <QuerySet [<UserGroup: group_python>]>
      <QuerySet [<UserGroup: group_python>, <UserGroup: group_linux>, <UserGroup: group_mysql>]>
      <QuerySet [<UserInfo: zhangsan>, <UserInfo: lisi>, <UserInfo: wangwu>]>

  7. 多對多雙下劃線查詢

    1. mdoels
      from django.db import models
      
      # 3.3 建立m2m多對多時ManyToManyField可以新增的引數
      """
      1、to, # 要進行關聯的表名
      2、related_name=None, # 反向操作時,使用的欄位名,用於代替 【表名_set】如: obj.
      表名_set.all()
      3、related_query_name=None, # 反向操作時,使用的連線字首,用於替換【表名】
      
      """
      
      # 自己建立第三張關係表,無 m2m 欄位,自己連結串列查詢
      # 表1:主機表
      class Host(models.Model):
          nid = models.AutoField(primary_key=True)
          hostname = models.CharField(max_length=32, db_index=True)
      
      
      # 表2:應用表
      class Application(models.Model):
          name = models.CharField(max_length=32)
      
      
      # 表3:自定義第三張關聯表
      class HostToApp(models.Model):
          hobj = models.ForeignKey(to="Host", to_field="nid", on_delete=models.CASCADE)
          aobj = models.ForeignKey(to='Application', to_field='id', on_delete=models.CASCADE)
      
      # # 向第三張表插入資料,建立多對多外來鍵關聯
      # HostToApp.objects.create(hobj_id=1, aobj_id=2)
      
    2. views
      from django.shortcuts import HttpResponse
      from app04 import models
      
      # 3.3 多對多雙下劃線查詢
      
      def orm5(request):
          # 第一種:values-----獲取的內部是字典,拿固定列數
          # 1.1 正向查詢: 使用ManyToManyField欄位名user_info結合雙下劃線查詢
          print(models.UserGroup.objects.filter(group_name='group_python').values('group_name', 'user_info__username'))
          # 1.2 反向查詢: 使用ManyToManyField的related_query_name='m2m',的欄位
          print(models.UserInfo.objects.filter(username='zhangsan').values('username', 'm2m__group_name'))
          # 第二種:values_list-----獲取的是元組 拿固定列數
          # 2.1 正向查詢: 使用ManyToManyField欄位名user_info結合雙下劃線查詢
          print(models.UserGroup.objects.filter(group_name='group_python').values_list('group_name', 'user_info__username'))
          # 2.2 反向查詢: 使用ManyToManyField的related_query_name='m2m',的欄位
          lesson = models.UserInfo.objects.filter(username='zhangsan').values_list('username', 'm2m__group_name')
          print(lesson)
          # 自動建立UserInfo表和UserGroup表中的資料
          '''
          # user_info_obj = models.UserInfo.objects.get(username='lisi')
          # user_info_objs = models.UserInfo.objects.all()
          #
          # group_obj = models.UserGroup.objects.get(group_name='group_python')
          # group_objs = models.UserGroup.objects.all()
          # group_obj.user_info.add(*user_info_objs)
          # user_info_obj.usergroup_set.add(*group_objs)
          user_list = [{'username':'zhangsan'},
          {'username':'lisi'},
          {'username':'wangwu'},]
          group_list = [{'group_name':'group_python'},
          {'group_name':'group_linux'},
          {'group_name':'group_mysql'},]
          for c in user_list:
          models.UserInfo.objects.create(**c)
          for l in group_list:
          models.UserGroup.objects.create(**l)
          '''
          return HttpResponse('orm')
      
    3. 資料庫結構
      空 只是看看錶結構
    4. 查詢返回

      <QuerySet [{‘group_name’: ‘group_python’, ‘user_info__username’: ‘zhangsan’}, {‘group_name’: ‘group_python’, ‘user_info__username’: ‘lisi’}, {‘group_name’: ‘group_python’, ‘user_info__username’: ‘wangwu’}]>
      <QuerySet [{‘username’: ‘zhangsan’, ‘m2m__group_name’: ‘group_python’}, {‘username’: ‘zhangsan’, ‘m2m__group_name’: ‘group_linux’}, {‘username’: ‘zhangsan’, ‘m2m__group_name’: ‘group_mysql’}]>
      <QuerySet [(‘group_python’, ‘zhangsan’), (‘group_python’, ‘lisi’), (‘group_python’, ‘wangwu’)]>
      <QuerySet [(‘zhangsan’, ‘group_python’), (‘zhangsan’, ‘group_linux’), (‘zhangsan’, ‘group_mysql’)]>

  8. 進階操作

    1. mdoels
      from django.db import models
      
      
      # Create your models here.
      
      
      class UserInfo(models.Model):
          username = models.CharField(max_length=32)
          password = models.CharField(max_length=132)
      
      
      class Student(models.Model):
          name = models.CharField(max_length=32)
          age = models.CharField(max_length=132)
      
    2. views
      from django.shortcuts import HttpResponse
      from . import models
      
      """
      
      4.2 進階操作:牛掰掰的雙下劃線
      
      1、大於,小於
      # models.Tb1.objects.filter(id__gt=1) # 獲取id大於1的值
      # models.Tb1.objects.filter(id__gte=1) # 獲取id大於等於1的值
      # models.Tb1.objects.filter(id__lt=10) # 獲取id小於10的值
      # models.Tb1.objects.filter(id__lte=10) # 獲取id小於等於10的
      值
      # models.Tb1.objects.filter(id__lt=10, id__gt=1) # 獲取id大於1 且 小於
      10的值
      2、in
      # models.Tb1.objects.filter(id__in=[11, 22, 33]) # 獲取id等於11、22、
      33的資料
      # models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in
      3、isnull
      # Entry.objects.filter(pub_date__isnull=True) #雙下劃線isnull,查詢
      pub_date是null的資料
      4、contains #就是原生sql的like操
      作:模糊匹配
      # models.Tb1.objects.filter(name__contains="ven")
      # models.Tb1.objects.filter(name__icontains="ven") # icontains大小寫不敏
      感
      # models.Tb1.objects.exclude(name__icontains="ven")
      5、range
      # models.Tb1.objects.filter(id__range=[1, 2]) # 範圍bettwen and
      6、order by
      # models.Tb1.objects.filter(name='seven').order_by('id') # asc
      沒有減號升續排列
      # models.Tb1.objects.filter(name='seven').order_by('-id') # desc
      有減號升續排列
      7、group by
      # from django.db.models import Count, Min, Max, Sum
      # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
      #根據id列進行分組
      4.3 時間查詢
      5.F()和Q()查詢語句
      # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM
      "app01_tb1"
      # WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"
      8、limit 、offset #分頁
      # models.Tb1.objects.all()[10:20]
      9、regex正則匹配,iregex 不區分大小寫
      # Entry.objects.get(title__regex=r'^(An?|The) +')
      # Entry.objects.get(title__iregex=r'^(an?|the) +')
      10、date
      # Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1))
      #__data表示日期查詢,2005-01-01
      # Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))
      # 2005-01-01以後建立的資料
      11、year
      # Entry.objects.filter(pub_date__year=2005)
      #__year根據年查詢
      # Entry.objects.filter(pub_date__year__gte=2005)
      12、month
      # Entry.objects.filter(pub_date__month=12)
      # Entry.objects.filter(pub_date__month__gte=6)
      13、day
      # Entry.objects.filter(pub_date__day=3)
      # Entry.objects.filter(pub_date__day__gte=3)
      14、week_day
      # Entry.objects.filter(pub_date__week_day=2)
      # Entry.objects.filter(pub_date__week_day__gte=2)
      15、hour
      # Event.objects.filter(timestamp__hour=23)
      # Event.objects.filter(time__hour=5)
      # Event.objects.filter(timestamp__hour__gte=12)
      16、minute
      # Event.objects.filter(timestamp__minute=29)
      # Event.objects.filter(time__minute=46)
      # Event.objects.filter(timestamp__minute__gte=29)
      17、second
      # Event.objects.filter(timestamp__second=31)
      # Event.objects.filter(time__second=2)
      # Event.objects.filter(timestamp__second__gte=31)
      """
      
      
      # 4.1 基礎查詢語句
      def orm6(request):
          # 1 建立
          # 建立資料方法一
          models.UserInfo.objects.create(username='root', password='123')
          # 建立資料方法二
          obj = models.UserInfo(username='alex', password='123')
          obj.save()
          # 建立資料庫方法三(傳入字典必須在字典前加兩個星號)
          dic = {'username': 'eric', 'password': '666'}
          models.UserInfo.objects.create(**dic)
          # 2 查
          result = models.UserInfo.objects.all()  # 查詢所有條目
          result = models.UserInfo.objects.filter(username='alex', password='123')
          for row in result:
              print(row.id, row.username, row.password)
          # 3 刪除
          models.UserInfo.objects.all().delete()  # 刪除所有
          # 4.2進階操作:牛掰掰的雙下劃線
          models.UserInfo.objects.filter(username='alex').delete()  # 刪除指定
          # 4 更新
          models.UserInfo.objects.all().update(password='12345')
          models.UserInfo.objects.filter(id=4).update(password='15')
          # 5 獲取個數
          models.UserInfo.objects.filter(name='seven').count()
          # 6 執行原生SQL
          # 6.1 執行原生SQL
          models.UserInfo.objects.raw('select * from userinfo')
          # 6.2 如果SQL是其他表時,必須將名字設定為當前UserInfo物件的主鍵列名
          models.UserInfo.objects.raw('select id as nid from 其他表')
          # 6.3 指定資料庫
          models.UserInfo.objects.raw('select * from userinfo', using="default")
          return HttpResponse('orm')
      
    3. 資料庫結構

      student

      id name age
      1 zhangsan 35
      2 lisi 22
      3 wangwu 33

      userinfo

      id username password
      12 root 12345
      13 alex 12345
      14 eric 12345

    4. 查詢返回

      13 alex 123

  9. 時間查詢

    1. mdoels
      
      
    2. views
      # 時間查詢
      # now = timezone.now()
      # # start_time = now - timezone.timedelta(days=7)
      # start_time = now - timezone.timedelta(hours=240)  # 查詢10天前的資料
      # end_time = now
      # qs = AllClarm.objects.filter(start_tm__range=(start_time, end_time))
      
    3. 資料庫結構
    4. 查詢返回
  10. F Q查詢

    1. mdoels
      from django.db import models
      # Create your models here.
      
      
      class Student(models.Model):
          name = models.CharField(max_length=32)
          age = models.CharField(max_length=132)
      
    2. views
      from django.db.models import F, Q
      
      
      def orm7(request):
          # stu_list = [{'name': 'zhangsan', 'age': 11},
          #             {'name': 'lisi', 'age': 22},
          #             {'name': 'wangwu', 'age': 33}, ]
          # for u in stu_list:
          #     models.Student.objects.create(**u)
          # 每訪問一次資料庫中zhangsan的年紀就會自動增加1
          models.Student.objects.filter(name='zhangsan').update(age=F("age") + 1)
          # 自動生成Student表中資料
          '''
          stu_list = [{'name':'zhangsan','age':11},
          {'name': 'lisi', 'age': 22},
          {'name': 'wangwu', 'age': 33},]
          for u in stu_list:
          models.Student.objects.create(**u)
          '''
          return HttpResponse('orm')
          
      def orm8(request):
          # 查詢學生表中年級大於1小於30姓zhang的所有學生
          stus = models.Student.objects.filter(
          Q(age__gt=1) & Q(age__lt=30),
          Q(name__startswith='zhang')
          )
          print('stu', stus)  # 執行結果:[<Student: zhangsan>]
          # 自動生成Student表中資料
          '''
          stu_list = [{'name':'zhangsan','age':11},
          {'name': 'lisi', 'age': 22},
          {'name': 'wangwu', 'age': 33},]
          for u in stu_list:
          models.Student.objects.create(**u)
          '''
          return HttpResponse('orm')
      
    3. 資料庫結構

      student

      id name age
      1 zhangsan 36
      2 lisi 22
      3 wangwu 33

    4. 查詢返回

      orm7 年齡加一

      orm8

      stu <QuerySet [<Student: Student object (22)>, <Student: Student object (25)>, <Student: Student object (28)>, <Student: Student object (31)>]>

  11. 聚合函式

    1. mdoels
      from django.db import models
      
      
      # Create your models here.
      
      class Student(models.Model):
          name = models.CharField(max_length=32)
          age = models.CharField(max_length=132)
      
    2. views
      # 6.1 ggregate聚合函式
      # 作用:從資料庫中取出一個彙總的集合
      # 6.2 annotate實現聚合group by查詢
      # 作用:對查詢結果進行分組,比如分組求出各年齡段的人數
      # 注: annotate後面加filter過濾相當於原生sql語句中的having
      def orm9(request):
          stus = models.Student.objects.aggregate(
              stu_num=Count('age'),  # 計算學生表中有多少條age條目
              stu_avg=Avg('age'),  # 計算學生的平均年紀
              stu_max=Max('age'),  # 找到年紀最大的學生
              stu_sum=Sum('age'))  # 將表中的所有年紀相加
          print('stu', stus)
          return HttpResponse('ok')
          # 執行結果:{'stu_sum': 69, 'stu_max': 24, 'stu_avg': 23.0, 'stu_num'
          
      def orm10(request):
          # 1 按年紀分組查詢學生表中各個年齡段學生人數:(22歲兩人,24歲一人)
          # 查詢結果:[{'stu_num': 2, 'age': 22}, {'stu_num': 1, 'age': 24}]
          stus1 = models.Student.objects.values('age').annotate(stu_num=Count('age'))
          # 2 按年紀分組查詢學生表中各個年齡段學生人數,並過濾出年紀大於22的:
          # 查詢結果:[{'stu_num': 1, 'age': 24}] (年級大於22歲的僅一人,年級為24歲)
          stus2 = models.Student.objects.values('age').annotate(stu_num=Count('age')).filter(age__gt=22)
          # 3 先按年紀分組,然後查詢出各個年齡段學生的平均成績
          # 查詢結果:[{'stu_Avg': 86.5, 'age': 22}, {'stu_Avg': 99.0, 'age': 24}]
          # 22歲平均成績:86.5 24歲平均成績:99
          stus3 = models.Student.objects.values('age').annotate(stu_Avg=Avg('age'))
          print(stus1, stus2, stus3)
          return HttpResponse('ok')
      
    3. 資料庫結構

      student

      id name age
      1 zhangsan 36
      2 lisi 22
      3 wangwu 33

    4. 查詢返回

      orm9

      stu {‘stu_num’: 33, ‘stu_avg’: 28.666666666666668, ‘stu_max’: ‘36’, ‘stu_sum’: 946.0}

      orm10

      <QuerySet [{‘age’: ‘36’, ‘stu_num’: 1}, {‘age’: ‘22’, ‘stu_num’: 11}, {‘age’: ‘33’, ‘stu_num’: 12}, {‘age’: ‘35’, ‘stu_num’: 1}, {‘age’: ‘34’, ‘stu_num’: 1}, {‘age’: ‘32’, ‘stu_num’: 1}, {‘age’: ‘31’, ‘stu_num’: 1}, {‘age’: ‘30’, ‘stu_num’: 1}, {‘age’: ‘29’, ‘stu_num’: 1}, {‘age’: ‘28’, ‘stu_num’: 1}, {‘age’: ‘27’, ‘stu_num’: 1}, {‘age’: ‘26’, ‘stu_num’: 1}]>

      <QuerySet [{‘age’: ‘36’, ‘stu_num’: 1}, {‘age’: ‘33’, ‘stu_num’: 12}, {‘age’: ‘35’, ‘stu_num’: 1}, {‘age’: ‘34’, ‘stu_num’: 1}, {‘age’: ‘32’, ‘stu_num’: 1}, {‘age’: ‘31’, ‘stu_num’: 1}, {‘age’: ‘30’, ‘stu_num’: 1}, {‘age’: ‘29’, ‘stu_num’: 1}, {‘age’: ‘28’, ‘stu_num’: 1}, {‘age’: ‘27’, ‘stu_num’: 1}, {‘age’: ‘26’, ‘stu_num’: 1}]>

      <QuerySet [{‘age’: ‘36’, ‘stu_Avg’: 36.0}, {‘age’: ‘22’, ‘stu_Avg’: 22.0}, {‘age’: ‘33’, ‘stu_Avg’: 33.0}, {‘age’: ‘35’, ‘stu_Avg’: 35.0}, {‘age’: ‘34’, ‘stu_Avg’: 34.0}, {‘age’: ‘32’, ‘stu_Avg’: 32.0}, {‘age’: ‘31’, ‘stu_Avg’: 31.0}, {‘age’: ‘30’, ‘stu_Avg’: 30.0}, {‘age’: ‘29’, ‘stu_Avg’: 29.0}, {‘age’: ‘28’, ‘stu_Avg’: 28.0}, {‘age’: ‘27’, ‘stu_Avg’: 27.0}, {‘age’: ‘26’, ‘stu_Avg’: 26.0}]>

相關文章