zoukankan      html  css  js  c++  java
  • python周报第二十周

    0.本周知识点预览

    • model 联表查询
    • model F/Q
    • model 多对多
    • 中间件
    • 缓存
    • 信号
    • 分页

    1.model 联表查询

    增删改查操作:

    #
        #
        # models.Tb1.objects.create(c1='xx', c2='oo')  增加一条数据,可以接受字典类型数据 **kwargs
    
        # obj = models.Tb1(c1='xx', c2='oo')
        # obj.save()
    
        #
        #
        # models.Tb1.objects.get(id=123)         # 获取单条数据,不存在则报错(不建议)
        # models.Tb1.objects.all()               # 获取全部
        # models.Tb1.objects.filter(name='seven') # 获取指定条件的数据
    
        #
        #
        # models.Tb1.objects.filter(name='seven').delete() # 删除指定条件的数据
    
        #
        # models.Tb1.objects.filter(name='seven').update(gender='0')  # 将指定条件的数据更新,均支持 **kwargs
        # obj = models.Tb1.objects.get(id=1)
        # obj.c1 = '111'
        # obj.save()                                                 # 修改单条数据

    model 字段类型:

    1、models.AutoField  自增列 = int(11)
      如果没有的话,默认会生成一个名称为 id 的列,如果要显示的自定义一个自增列,必须将给列设置为主键 primary_key=True。
    2、models.CharField  字符串字段
      必须 max_length 参数
    3、models.BooleanField  布尔类型=tinyint(1)
      不能为空,Blank=True
    4、models.ComaSeparatedIntegerField  用逗号分割的数字=varchar
      继承CharField,所以必须 max_lenght 参数
    5、models.DateField  日期类型 date
      对于参数,auto_now = True 则每次更新都会更新这个时间;auto_now_add 则只是第一次创建添加,之后的更新不再改变。
    6、models.DateTimeField  日期类型 datetime
      同DateField的参数
    7、models.Decimal  十进制小数类型 = decimal
      必须指定整数位max_digits和小数位decimal_places
    8、models.EmailField  字符串类型(正则表达式邮箱) =varchar
      对字符串进行正则表达式
    9、models.FloatField  浮点类型 = double
    10、models.IntegerField  整形
    11、models.BigIntegerField  长整形
      integer_field_ranges = {
        'SmallIntegerField': (-32768, 32767),
        'IntegerField': (-2147483648, 2147483647),
        'BigIntegerField': (-9223372036854775808, 9223372036854775807),
        'PositiveSmallIntegerField': (0, 32767),
        'PositiveIntegerField': (0, 2147483647),
      }
    12、models.IPAddressField  字符串类型(ip4正则表达式)
    13、models.GenericIPAddressField  字符串类型(ip4和ip6是可选的)
      参数protocol可以是:both、ipv4、ipv6
      验证时,会根据设置报错
    14、models.NullBooleanField  允许为空的布尔类型
    15、models.PositiveIntegerFiel  正Integer
    16、models.PositiveSmallIntegerField  正smallInteger
    17、models.SlugField  减号、下划线、字母、数字
    18、models.SmallIntegerField  数字
      数据库中的字段有:tinyint、smallint、int、bigint
    19、models.TextField  字符串=longtext
    20、models.TimeField  时间 HH:MM[:ss[.uuuuuu]]
    21、models.URLField  字符串,地址正则表达式
    22、models.BinaryField  二进制
    23、models.ImageField   图片
    24、models.FilePathField 文件

    双下划线操作:

    # 获取个数
        #
        # models.Tb1.objects.filter(name='seven').count()
    
        # 大于,小于
        #
        # models.Tb1.objects.filter(id__gt=1)              # 获取id大于1的值
        # models.Tb1.objects.filter(id__lt=10)             # 获取id小于10的值
        # models.Tb1.objects.filter(id__lt=10, id__gt=1)   # 获取id大于1 且 小于10的值
    
        # 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
    
        # contains
        #
        # models.Tb1.objects.filter(name__contains="ven")
        # models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
        # models.Tb1.objects.exclude(name__icontains="ven")
    
        # range
        #
        # models.Tb1.objects.filter(id__range=[1, 2])   # 范围bettwen and
    
        # 其他类似
        #
        # startswith,istartswith, endswith, iendswith,
    
        # order by
        #
        # models.Tb1.objects.filter(name='seven').order_by('id')    # asc
        # models.Tb1.objects.filter(name='seven').order_by('-id')   # desc
    
        # limit 、offset
        #
        # models.Tb1.objects.all()[10:20]
    
        # group by
        from django.db.models import Count, Min, Max, Sum
        # models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
        # SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"

    实例:

    数据库python代码:

    from django.db import models
    
    # Create your models here.
    
    class UserType(models.Model):
        catption = models.CharField(max_length=32)
    
    # 超级管理员,普通用户,游客,黑河
    
    class UserInfo(models.Model):
    
        user = models.CharField(max_length=32)
        pwd = models.CharField(max_length=32)
        user_type = models.ForeignKey('UserType')
        # user_type_id

    python django代码:

    def sqltest(request):
        # result = models.UserType.objects.all()
        # ###输出所有用户类型
        # for i in result:
        #     print(i.catption)
        ###输出所有高富帅的用户名(查表两遍)
        # uid = models.UserType.objects.get(catption='高富帅').id
        # result = models.UserInfo.objects.filter(user_type_id=uid)
        # print([ r.user for r in result])
        ###利用外键反查用户类型表的用户类型
        # print([r.user_type.catption for r in result])
        ###输出所有高富帅的用户名(查表一遍)(利用双下划线!!!)
        # result = models.UserInfo.objects.filter(user_type__catption="高富帅")
        # print([r.user for r in result])
        ###输出所有高富帅的用户名(查表一遍)返回字典形式
        # result = models.UserInfo.objects.filter(user_type__catption="高富帅").values("user")
        # print([r["user"] for r in result])
        ###输出所有高富帅的用户名(查表一遍)返回元组形式
        # result = models.UserInfo.objects.filter(user_type__catption="高富帅").values_list("user")
        # print([r[0] for r in result])
        return HttpResponse("ok")

    2.model F/Q

    # F 使用查询条件的值
        #
        # from django.db.models import F
        # models.Tb1.objects.update(num=F('num')+1)
    
        # Q 构建搜索条件
        from django.db.models import Q
        # con = Q()
        #
        # q1 = Q()
        # q1.connector = 'OR'
        # q1.children.append(('id', 1))
        # q1.children.append(('id', 10))
        # q1.children.append(('id', 9))
        #
        # q2 = Q()
        # q2.connector = 'OR'
        # q2.children.append(('c1', 1))
        # q2.children.append(('c1', 10))
        # q2.children.append(('c1', 9))
        #
        # con.add(q1, 'AND')
        # con.add(q2, 'AND')
        #
        # models.Tb1.objects.filter(con)
    
        #
        # from django.db import connection
        # cursor = connection.cursor()
        # cursor.execute("""SELECT * from tb where name = %s""", ['Lennon'])
        # row = cursor.fetchone()

    3.model 多对多查询

    user_info_obj = models.UserInfo.objects.get(name=u'武沛齐')
    user_info_objs = models.UserInfo.objects.all()
     
    group_obj = models.UserGroup.objects.get(caption='CEO')
    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()
    #print group_obj.user_info.all().filter(id=1)
     
    # 获取数据
    #print user_info_obj.usergroup_set.all()
    #print user_info_obj.usergroup_set.all().filter(caption='CEO')
    #print user_info_obj.usergroup_set.all().filter(caption='DBA')
    xx_set中的_set是多对多的固定搭配   表名_set

    django 缓存、分页、信号最佳博客链接:http://www.cnblogs.com/wupeiqi/articles/5246483.html

    django 完整文档:http://docs.30c.org/djangobook2/chapter07/

  • 相关阅读:
    const---ES6的新特性---从js角度理解
    mpvue搭建微信小程序
    get和post区别,面试中经典答法
    Deno增删查改(CRUD)应用
    Thymeleaf货币转换
    Spring Security和Spring Core 依赖冲突
    Java15于2020/09/15发版
    WebFlux系列(十三)MySql应用新增、修改、查询、删除
    WebFlux系列(十二)MongoDB应用,新增、修改、查询、删除
    Spring Boot(4) Mongo数据库新增、删除、查询、修改
  • 原文地址:https://www.cnblogs.com/Caesary/p/5885763.html
Copyright © 2011-2022 走看看