ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

聚合函数、分组查询、F与Q查询、ORM查询优化、ORM字段类型及参数、ORM事务操作md

2022-05-18 23:31:22  阅读:159  来源: 互联网

标签:md objects models res price 查询 ORM Book print


聚合查询

分组查询

F与Q查询

ORM查询优化

ORM字段类型及参数

ORM事务操作

聚合查询

MySQL聚合函数:
"""
    max				统计最大值
    min				统计最小值
    sum				统计求和
    count			统计计数
    avg				统计平均值
"""
'''使用关键字段:aggregater'''
操作方法:
    from django.db.models import Max, Min, Sum, Avg, Count
    res = models.BOOK.objects.aggregater(Max('price'))
    print(res)
    
# 查看价格最高、最低、价格之和、平均价格、书本个数
    res = models.Book.objects.aggregate(Max('price'),
                                        Min('price'),
                                        Sum('price'),
                                        Avg('price'),
                                        Count('pk')
                                        )
    print(res)  # {'price__max': Decimal('9999.00'), 'price__min': Decimal('5999.00'), 'price__sum': Decimal('43863.00'), 'price__avg': 8772.6, 'pk__count': 5}

分组查询

'''MySQL分组操作: group by 关键字: annotate''' 
ORM执行分组操作,报错的话就去修改sql_mode 移除only_full_group_by

# 先按表为单位分组
from django.db.models import Max, Min, Sum, Avg, Count
    #  统计每本书的作者个数
    # 书查作者,正向查询
 res = models.Book.objects.annotate(author_num=Count('authors__pk')).values('title', 'author_num')
print(res)  # <QuerySet [{'title': 'python全栈', 'author_num': 1}, {'title': 'linux云计算', 'author_num': 2}, {'title': 'golang高并发', 'author_num': 2}, {'title': '葵花点穴手', 'author_num': 0}, {'title': '西游记', 'author_num': 0}]>

    # 统计每个出版社卖的最便宜的书的价格
    # 出版社查书,方向
res = models.Publish.objects.annotate(min_price=Min('book__price')).values('name', 'min_price')
print(res)  # <QuerySet [{'name': '北京出版社', 'min_price': Decimal('5999.00')}, {'name': '南京出版社', 'min_price': Decimal('9988.00')}, {'name': '西北出版社', 'min_price': Decimal('8888.00')}]>

    # 统计不止一个作者的图书
res = models.Book.objects.annotate(author_num=Count('authors__pk')).filter(author_num__gt=1).values('title',                                                'author_num')
print(res)  # <QuerySet [{'title': 'linux云计算', 'author_num': 2}, {'title': 'golang高并发', 'author_num': 2}]>

    # 统计每个作者出的书的价格
res = models.Author.objects.annotate(book_sum_price=Sum('book__price')).values('name', 'book_sum_price')
print(res)  # <QuerySet [{'name': 'gavin', 'book_sum_price': Decimal('17877.00')}, {'name': 'tom', 'book_sum_price': Decimal('27865.00')}, {'name': 'mary', 'book_sum_price': None}]>

'''使用表中的字段分组'''
# 统计每个出版社主键值对应的书籍个数
res = models.Book.objects.values('publish_id').annotate(book_num=Count('pk')).values('publish_id', 'book_num')
print(res)  # <QuerySet [{'publish_id': 1, 'book_num': 2}, {'publish_id': 2, 'book_num': 2}, {'publish_id': 3, 'book_num': 1}]>

F与Q查询

"""
 当表中已经有数据的情况下,添加额外的字段、需要指定默认值或者为null
   方式一:
     IntegerField(verbose_name='销量',default=1000)
   方式二:
     IntegerField(verbose_name='销量',null=True)
   方式三:
	 在迁移命令提示中直接给默认值
"""
    # 查看库存大于销量的书籍
    # 使用F查询
    from django.db.models import F
    res = models.Book.objects.filter(kucun__gt=F('xiaoliang'))
    print(res)  # [<Book: 书籍对象:linux云计算>, <Book: 书籍对象:葵花点穴手>, <Book: 书籍对象:西游记>]>

    # 将所有的价格提升1000块
    # 查到书的价格,然后加1000
    res = models.Book.objects.update(price=F('price')+1000)

    # 将所有书的名称后面加上_爆款
    res = models.Book.objects.update(title=F('title')+'_爆款')  # 直接给清空了
    from django.db.models.functions import Concat
    from django.db.models import Value
    res = models.Book.objects.update(title=Concat(F('title'),Value('爆款')))

  • Q查询

# 查询价格大于9888或者卖出大于500的书
    # 这里要使用到或的关系,因为filter括号内为and关系,并且不能修改,所以使用Q
    from django.db.models import Q
    '''使用Q对象,我们就可以做逻辑运算符'''
    res = models.Book.objects.filter(Q(price__gt=9888), Q(xiaoliang__gt=500))
    print(res.query)  # `price` > 9888 AND `app01_book`  逗号是and关系
    res = models.Book.objects.filter(Q(price__gt=9888) | Q(xiaoliang__gt=500))
    print(res.query)  # `price` > 9888 OR `app01_book` 管道符为or关系
    res = models.Book.objects.filter(~Q(price__gt=9888))
    print(res.query)  # WHERE NOT (`app01_book`.`price` > 9888)  ~是not关系 取反
    
'''
   Q对象进阶用法
        filter(price=100)
        filter('price'=100)
    当我们需要编写一个搜索功能 并且条件是由用户指定 这个时候左边的数据就是一个字符串
    '''
        
    q_obj = Q()
    q_obj.connector = 'or'  # 链接修改为or ,默认为and
    q_obj.children.append(('price__gt', 9888))
    q_obj.children.append(('xiaoliang__gt', 530))
    res = models.Book.objects.filter(q_obj)
    # print(res.query)
    print(res)

ORM查询优化

"""
  在IT行业,需要做到尽量不麻烦数据库就不麻烦数据库,
"""
# 1、orm查询默认都是惰性查询,不消耗数据库就不消耗
  res = models.Book.objects.all()  # 只写这一句不走数据库
    print(res)  # 得到列表套对象
    
# orm查询默认自带分页功能
res = models.Book.objects.values('title','price')
    for i in res:
        print(i.get('title'))
        
res = models.Book.objects.only('title', 'price')
    for obj in res:
        print(obj.title)
        print(obj.price)  # 点存在的字段数据库走两行
        print(obj.publish_time)  # 有几个结果,走几次
"""
  only会产生对象结果集,对象点括号内的字段不会再走数据库查询, 
  点括号里面没有的,也可以获取数据,但是每次都会走数据库查询
"""        
res = models.Book.objects.defer('title', 'price')
    for obj in res:
        print(obj.title)
        print(obj.price)  # 点存在的字段,几个结果获取几个,数据库跑几个
        print(obj.publish_time)  # 点不存在的字段,不走数据库
 """
   defer与only相反,对象点括号内出现的字段就会走数据库查询, 点括号不存在的数据,也会得到,而且不走数据库查询
 """

#  select_related和prefetch_related 区别
# 查看出版社的资料
res = models.Book.objects.select_related('publish')
    for obj in res:
        print(obj.title)
        print(obj.publish.name)  # 出版社名称
        print(obj.publish.addr)  # 出版社地址
"""
 select_related括号内只能一对一和一对多字段,不能传多对多字段,
  效果是内部直接连接表(inner join) 然后将连接之后的大表中所有的数据全部封装到数据对象中,后面对象通过正反向查询跨表,内部不会再走数据库查询
"""
   res = models.Book.objects.prefetch_related('publish')
    for obj in res:
        print(obj.title)
        print(obj.publish.name)
        print(obj.publish.addr)
    """
    将多次查询之后的结果封装到数据对象中 后续对象通过正反向查询跨表 内部不会再走数据库查询
    """

ORM字段类型及参数

AutoField()         int auto_increment

CharField()         必须写max_length参数 varchar类型

IntergerField()     int 整型

DecimalField()      decimal  
	
DateField()
	date		    两种  auto_now   auto_now_add
DateTimeField()
	datetime		两种  auto_now   auto_now_add
    
BigIntergerField()    bigint      

BooleanField()        传布尔值 存0和1

TextField()           存储大段文本

FileField()       传文件自动保存到指定位置并存文件路径

EmailField()      本质还是varchar类型 
 
# 自定义字段类型
class MyCharField(models.Field):
    def __init__(self, max_length, *args, **kwargs):
        self.max_length = max_length
        super().__init__(max_length=max_length, *args, **kwargs)
        
    def db_type(self, connection):
         """
        返回真正的数据类型及各种约束条件
        :param connection:
        :return:
        """
        return 'char(%s)' % self.max_length
# 自定义字段类型使用
myfield = MyCharField(max_length=32,null=True)
  • ORM重要参数

primary_key      主键  
max_length       最长
verbose_name     简介
null             空
default          默认值
max_digits       decimal最大长度
decimal_places   小数点后位数
unique           唯一
db_index         索引
auto_now         表改变自动更新
auto_now_add     创建记录添加日期
choices          类似于枚举
to               创建外键指定被关联内容
to_field         创建外键指定被关联自字段
db_constraint	是否在数据库中创建外键约束
related_name	修改正向查询的字段名
#  choices的使用
	用于可以被列举完全的数据
  	eg:性别 学历 工作经验 工作状态
      	class User(models.Model):
          username = models.CharField(max_length=32)
          password = models.IntegerField()
          gender_choice = (
              (1,'男性'),
              (2,'女性'),
              (3,'中性')
          )
          gender = models.IntegerField(choices=gender_choice)
				user_obj.get_gender_display()  
       
res = models.User.objects.get('pk=2')
res.get_gender_display()  # 女性
当值为1 获取男性 
当值为2 获取女性 
当值为3 获取中性 
当值不存在的时候, 直接返回输入的数值
"""
外键字段中使用related_name参数可以修改正向查询的字段名
"""

ORM事务操作

# MySQL事务:四大特性(ACID)
  	原子性
    一致性
    独立性
    持久性
# 操作关键字
    start transcation;   # 开启事务
    rollback;  # 回滚
    commit;    # 确认提交,之后不能再回滚
  
from django.db import transaction
    try:
        with transaction.atomic():
            pass
    except Exception:
        pass
 # 创建异常捕获, 执行完成自动提交, 异常自动数据回滚
  • ORM执行原生SQL
# 方式1
 from django.db import connection, connections

    cursor = connection.cursor()
    # cursor = connections['default'].cursor()
    cursor.execute("""SELECT * from app01_author where id = %s""", [4])
    res = cursor.fetchone()
    print(res)  # (4, 'gavin', 29, 1)


# 方式2
models.UserInfo.objects.extra(
                    select={'newid':'select count(1) from app01_usertype where id>%s'},
                    select_params=[1,],
                    where = ['age>%s'],
                    params=[18,],
                    order_by=['-age'],
                    tables=['app01_book']
                )
# 使用
res = models.Book.objects.extra(
        select={'newid': 'select count(1) from app01_book where id>%s'},
        select_params=[1, ],
    )
    print(res)  # <QuerySet [<Book: 书籍对象:python全栈>, <Book: 书籍对象:golang高并发爆款>, <Book: 书籍对象:Linux云计算爆款>, <Book: 书籍对象:葵花点穴手爆款>, <Book: 书籍对象:西游记爆款>]>
  • 多对多三种创建方式

# 全自动(常见)
	orm自动创建第三张表 但是无法扩展第三张表的字段
	authors = models.ManyToManyField(to='Author')
# 全手动(使用频率最低)
	优势在于第三张表完全自定义扩展性高 劣势在于无法使用外键方法和正反向
	class Book(models.Model):
    title = models.CharField(max_length=32)
  class Author(models.Model):
    name = models.CharField(max_length=32)
  class Book2Author(models.Model):
    book_id = models.ForeignKey(to='Book')
    author_id = models.ForeignKey(to='Author')
# 半自动(常见)
	正反向还可以使用 并且第三张表可以扩展 唯一的缺陷是不能用  add\set\remove\clear  四个方法
  
class Book(models.Model):
    title = models.CharField(max_length=32)
    authors = models.ManyToManyField(
      					to='Author',
    						          through='Book2Author',  # 指定表
      					through_fields=('book','author')  # 指定字段
    )
class Author(models.Model):
    name = models.CharField(max_length=32)
    '''多对多建在任意一方都可以 如果建在作者表 字段顺序互换即可'''
    books = models.ManyToManyField(
      					to='Author',
    					through='Book2Author',  # 指定表
      					through_fields=('author','book')  # 指定字段
    )
  class Book2Author(models.Model):
    book = models.ForeignKey(to='Book')
    author = models.ForeignKey(to='Author')
   

图片

标签:md,objects,models,res,price,查询,ORM,Book,print
来源: https://www.cnblogs.com/lsw8898/p/16286729.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有