zoukankan      html  css  js  c++  java
  • 数据查询

    聚合查询 :

    #级联更新 : 
    	->表与表之间通过外键相关联 ,即外键字段对表之间会形成一种约束,表与表的数据一起更新 / 删除;
    
    当通过操作外键字段管理数据的时候 :
    	书跟出版社是一对多关系 (外键字段在书那儿)
            如果你把出版社删了 所对应的书也会自动删除
            如果你把出版社主键值改变了 那么书籍表中对应的出版社主键值也会自动修改
    
    

    聚合函数 :

    from django.db.models import Max, Min ,Sum ,Avg ,Count
    
    models.Book.objects.all().aggregate(Avg("price"))
    {'price__avg': 13.233333}
    
    注意:
     1.函数 : Max, Min ,Sum ,Avg ,Count
     2.导入函数,使用函数通过 : 关键字 aggregate() 
     3.aggregate()  它返回一个包含一些键值对的字典
     4.只要跟数据库相关的功能 基本上都在django.db.models或在django.db里面
     5.分组后 + 聚合函数 --》数据处理
    

    分组查询

    -->group by
    
    sql语句 : select dept,AVG(salary) from employee group by dept;
    
    ORM查询:
    from django.db.models import Avg
    Employee.objects.values("dept").annotate(avg=Avg("salary").values(dept, "avg")
                                             
    注意 :                                        
      1. 通过关键字 :annotate分组依据就是他前面的值,没有则默认用 id
      2.annotate本身表示group by的作用,前面找寻分组依据,内部放置显示可能用到的聚合运算式,后面跟filter来增加限制条件,最后的value来表示分组后想要查找的字段值
    
    
    实列1:
    from django.db.models import Max, Min, Sum, Count, Avg
    
    # 1.筛选出价格最高的书籍的
    res = models.Book.objects.aggregate(mr = Max('price'))
    print(res)
    # 2.一起使用
    res = models.Book.objects.aggregate(Max('price'),Min('price'),Sum('price'),Count('price'),Avg('price'))
    print(res)
    
    实列2:
    # 1.统计每一本书的作者个数 书名 和对应的作者人数
    res = models.Book.objects.annotate(author_num=Count('authors__id')).values('title','author_num')
    print(res)
    
    # 2.再筛选出大于一的图书  书名 作者数目
    res = models.Book.objects.annotate(author_num=Count('authors')).filter(author_num__gt=1).values('title','author_num')
    print(res)
    
    # 3.查询各个作者出的书的总价格  作者名字  总价格
    res = models.Author.objects.annotate(sum_price=Sum('book__price')).values('name','sum_price')
    print(res)
    

    F 与 Q 查询

    F: F() 的实例可以在查询中引用字段,来比较同一个 model 实例中两个不同字段的值。
    
    from django.db.models import F
    ret1=models.Product.objects.filter(maichu__gt=F('kucun'))
    print(ret1)
    
    F可以取到表中某个字段对应的值来当作筛选条件,而不是自定义常量的条件,实现了动态比较的效果
    
    Django 支持 F() 对象之间以及 F() 对象和常数之间的加减乘除和取模的操作。基于此可以对表中的数值类型进行数学运算
    
    将每个商品的价格提高50块: 
    models.Product.objects.update(price=F('price')+50
    
    -->修改char字段 :
    from django.db.models.functions import Concat
    from django.db.models import Value
    ret3=models.Product.objects.update(name=Concat(F('name'),Value('新款')))    
    
    Concat表示进行字符串的拼接操作,参数位置决定了拼接是在头部拼接还是尾部拼接,Value里面是要新增的拼接值                         
    
    Q : filter() 等方法中逗号隔开的条件是与的关系, 执行更复杂的查询(OR ~) 
    
    from django.db.models import Q
    Q查询 :filter() 默认链接是and 关系  --》模块修改
            --》 filter(Q(条件)| Q(条件))   或者
            --》 filter(~Q(条件)| Q(条件))   ~ 取反(not)
    
    高级用法: 
    q = Q()
    q.connector = 'or'  #修改默认之间的关系 (默认and)
    q.children.append((字符串1,字符串2))   #key , value
    res = models.Book.objects.filter(q)
    print(res)
    
    查询函数可以混合使用Q 对象和关键字参数。所有提供给查询函数的参数(关键字参数或Q 对象)都将"AND”在一起。但是,如果出现Q 对象,它必须位于所有关键字参数的前面
    

    常用orm 字段,参数:

    CharField     varchar
    IntegerField   int
    BigIntegerField   bigint
    EmailField    varchar(254)
    DateField
    DateTimeField
    auto_now:每次修改数据的时候 都会自动将当前修改时间更新上去  实时更新
    auto_now_add:在创建数据的时候 会将当前时间自动记录 之后不会自动修改  除非你人为修改
    
    AutoField     auto_increment   
    
    BooleanField    布尔值  
    该字段在存储的时候 你只需要传布尔值True或False
    它会自动存成1/0
    
    TextField  专门用来存大段文本
    
    FileField  专门用来文件路径   '/etc/data/a.txt'   
    upload_to = '/etc/data'
    给该字段传值的时候 直接传文件对象
    会自动将文件对象保存到upload_to后面指定的文件路径中
    然后将路径保存到数据库
    
    DecimalField(Field)
    - 10进制小数
    - 参数:
    max_digits,小数总长度
    decimal_places,小数位长度
    

    orm 内的事务操作:

    事务:		
        将多个sql语句操作变成原子性操作,要么同时成功,有一个失败则里面回滚到原来的状态,保证数据的完整性和一致性
    
    orm事务:
        from django.db.models import F
        from django.db import transaction
        # 开启事务处理
        try:
            with transaction.atomic():
                # 创建一条订单数据
                models.Order.objects.create(num="110110111", product_id=1, count=1)
                # 能执行成功
                models.Product.objects.filter(id=1).update(kucun=F("kucun")-1, maichu=F("maichu")+1)
        except Exception as e:
            print(e)
    
    特性: 原子性  , 一致性 ,隔离性  , 持久性
    
  • 相关阅读:
    1024X768大图 (Wallpaper)
    (Mike Lynch)Application of linear weight neural networks to recognition of hand print characters
    瞬间模糊搜索1000万基本句型的语言算法
    单核与双核的竞争 INTEL P4 670对抗820
    FlashFTP工具的自动缓存服务器目录的功能
    LDAP over SSL (LDAPS) Certificate
    Restart the domain controller in Directory Services Restore Mode Remotely
    How do I install Active Directory on my Windows Server 2003 server?
    指针与指针变量(转)
    How to enable LDAP over SSL with a thirdparty certification authority
  • 原文地址:https://www.cnblogs.com/shaozheng/p/11952830.html
Copyright © 2011-2022 走看看