ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

聚合查询 分组查询 F与Q查询 ORM查询优化 ORM常见字段 重要参数 事务操作 ORM执行原生SQL 多对多三种创建方式

2022-05-23 23:32:49  阅读:138  来源: 互联网

标签:__ Book objects models res price 查询 ORM SQL


day56 

 

 

聚合查询

  mysql聚合函数对一组值执行计算,并返回单个值,也被称为组函数。常见的聚合函数如下:

    count()、sum()、avg()、min()、max();

  使用这些函数需要aggregate关键字来调用。 返回值是一个字典

代码示例:

"""使用聚合函数之前需要先导入模块"""
from django.db.models import Max, Min, Sum, Avg, Count

res = models.Book.objects.aggregate(Max('price'))
print(res)  # {'price__max': Decimal('56777.98')}
'''没有分组如果使用聚合函数 默认是把整体数据当成是一组'''

res = models.Book.objects.aggregate(Max('price'),
                                        Min('price'),
                                        Sum('price'),
                                        Avg('price'),
                                        Count('pk')
                                        )  # 也可以一次性使用全部聚合函数
print(res)
{'price__max': Decimal('56777.98'), 'price__min': Decimal('16987.22'), 'price__sum': Decimal('179408.51'), 'price__avg': 29901.418333, 'pk__count': 6}

 

分组查询

MySQL分组操作:group by

ORM 分组操作:annotate()

ORM执行分组操作 如果报错

   可能需要去修改sql_mode 移除only_full_group_by

代码示例:

# 统计每本书的作者个数
from django.db.models import Count
res = models.Book.objects.annotate(author_num=Count('authors__pk')).values('title', 'author_num')

# 统计每个出版社卖的最便宜的书的价格
from django.db.models import Min
res = models.Publish.objects.annotate(min_price=Min('book__price')).values('name', 'min_price')  


# 统计不止一个作者的图书
from django.db.models import Count
res = models.Book.objects.annotate(author_num=Count('authors__pk')).filter(author_num__gt=1).values('title','author_num')


# 统计每个作者出的书的总价格
from django.db.models import Sum
res = models.Author.objects.annotate(book_sum_price=Sum('book__price')).values('name','book_sum_price')

    
"""上述操作都是以表为单位做分组 如果想要以表中的某个字段分组如何操作"""
models.Author.objects.values('age').annotate()
"""
如果.values()在.annotate()后面按照Author做分组
但是.values()在. annotate()前面按照表中的字段分组
"""
# 统计每个出版社主键值对应的书籍个数
from django.db.models import Count
    res = models.Book.objects.values('publish_id').annotate(book_num=Count('pk')).values('publish_id','book_num')
    print(res)

 

F与Q查询

当表中已经有数据的情况下 添加额外的字段 需要指定默认值或者可以为null


    方式1
        IntegerField(verbose_name='销量',default=1000)
    方式2
        IntegerField(verbose_name='销量',null=True)
    方式3
        在迁移命令提示中直接给默认值

代码示例:

# 查询库存大于销量的书籍
# res = models.Book.objects.filter(kucun > maichu)    不行
# res = models.Book.objects.filter(kucun__getmaichu)  不行# 当查询条件的左右两表的数据都需要表中的数据 可以使用F查询
from django.db.models import F
res = models.Book.objects.filter(kucun__gt=F('maichu'))

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

# 将所有书的名称后面加上_爆款后缀
res = models.Book.objects.update(title=F('title') + '_爆款')  # 不可以
'''如果要修改char字段咋办(千万不能用上面对数值类型的操作!!!) 需要使用下列两个方法'''
from django.db.models.functions import Concat
from django.db.models import Value
res = models.Book.objects.update(name=Concat(F('title'), Value('爆款')))
# 查询价格大于20000或者卖出大于1000的书籍
    # res = models.Book.objects.filter(price__gt=20000,maichu__gt=1000)
    # print(res)
    # print(res.query)
    '''filter括号内多个条件默认是and关系 无法直接修改'''
    from django.db.models import Q
    '''使用Q对象 就可以支持逻辑运算符'''
    # res = models.Book.objects.filter(Q(price__gt=20000), Q(maichu__gt=1000))  # 逗号是and关系
    # res = models.Book.objects.filter(Q(price__gt=20000) | Q(maichu__gt=1000))  # 管道符是or关系
    # res = models.Book.objects.filter(~Q(price__gt=20000))  # ~是not操作
    # print(res.query)

Q对象进阶用法
        filter(price=100)
        filter('price'=100)
    当我们需要编写一个搜索功能 并且条件是由用户指定 这个时候左边的数据就是一个字符串   

代码示例:

 q_obj = Q()
    q_obj.connector = 'or'  # 默认是and 可以改为or
    q_obj.children.append(('price__gt',20000))
    q_obj.children.append(('maichu__gt',1000))
    res = models.Book.objects.filter(q_obj)
    print(res.query)

 

ORM查询优化

1.orm查询默认都是惰性查询(能不消耗数据库资源就不消耗)


    光编写orm语句并不会直接指向SQL语句 只有后续的代码用到了才会执行


2.orm查询默认自带分页功能(尽量减轻单次查询数据的压力)

# 前几年django面试经常问
  only与defer

# 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):
        return 'char(%s)' % self.max_length

重要参数

primary_key
max_length
verbose_name
null
default
max_digits
decimal_places
unique
db_index
auto_now
auto_now_add
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()  
        # 有对应关系就拿 没有还是本身
to
to_field
db_constraint
ps:外键字段中可能还会遇到related_name参数
"""
外键字段中使用related_name参数可以修改正向查询的字段名
"""

事务操作

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 auth_user where id = %s""", [1])
cursor.fetchone()

# 方式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_usertype']
                )

多对多三种创建方式

# 全自动(常见)
	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')
    

 

标签:__,Book,objects,models,res,price,查询,ORM,SQL
来源: https://www.cnblogs.com/jiqiong/p/16303862.html

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

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

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

ICode9版权所有