python学习Day56-django

目录

django

聚合查询和分组查询

聚合(利用聚合函数)

聚合查询是根据sql语句中的五个聚合函数查询(max最大 min最小 sun求和 cont统计 avg求平均)

# 注意在Django语句中使用聚合函数,需要用到关键字‘aggregate’

aggregate()是QuerySet 的一个终止子句,意思是说,它返回一个包含一些键值对的字典。

键的名称是聚合值的标识符,值是计算出来的聚合值。键的名称是按照字段和聚合函数的名称自动生成出来的。

用到的内置函数:

from django.db.models import Avg, Sum, Max, Min, Count
# MySQL聚合函数:
	max\min\sum\count\avg

示例:

from django.db.models import Max, Min, Sum, Avg, Count

res = models.Book.objects.aggregate(Max('price'))
print(res)  # {'price__max': Decimal('56777.98')}
'''没有分组也可以使用聚合函数 默认整体就是一组'''
'''如果希望生成不止一个聚合,可以向aggregate()子句中添加另一个参数。'''
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}

分组

对应sql语句中的group by,ORM使用分组需要用到关键字annotate

SQL语句复习

假设现在有一张公司职员表:

按照部分分组求平均工资
'''MySQL分组操作: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")
这里需要注意的是annotate分组依据就是他前面的值,
如果前面没有特点的字段,则默认按照ID分组,
这里有dept字段,所以按照dept字段分组
连表查询的分组

# SQL查询
select dept.name,AVG(salary) from employee inner join dept on (employee.dept_id=dept.id) group by dept_id;
# ORM查询
from django.db.models import Avg
models.Dept.objects.annotate(avg=Avg("employee__salary")).values("name", "avg")

更多实例

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')

# 统计每个出版社卖的最便宜的书的价格
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()
# 统计每个出版社主键值对应的书籍个数
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)

总结

value里面的参数对应的是sql语句中的select要查找显示的字段,

filter里面的参数相当于where或者having里面的筛选条件

annotate本身表示group by的作用,前面找寻分组依据,内部放置显示可能用到的聚合运算式,后面跟filter来增加限制条件,最后的value来表示分组后想要查找的字段值

F与Q查询

F查询

F是Django框架中db.models中sql语句一个F类,可以拿到数据库表字段的原数据,方便我们对数据库中数据的修改和查找

F查询可以操作数字和字符串

'''F查询'''
    from django.db.models import F

    # 1、把所有书籍提价100
    # F查询默认操作的是数字
    models.Book.objects.update(price=F('price') + 100)

    # 2、把所有的书籍标题后面都加上'经典版'
    # F查询要操作字符串需要导入两个模块
    from django.db.models.functions import Concat
    from django.db.models import Value

    models.Book.objects.update(title=Concat(F('title'), Value('经典版')))

Q查询

Q查询主要用来为我们解决ORM框架操作sql语句中的(or)关系

'''Q查询'''

    # 1、查询书籍价格不低于300的或者标题为狂人日记的书籍
    from django.db.models import Q

    res = models.Book.objects.filter(Q(price__gt=300) | Q(title='狂人日记')).values_list()
    print(res)
    # <QuerySet [(2, '西游经典版', Decimal('400.00'), 3), (3, '水浒经典版', Decimal('500.00'), 2), (5, '狂人日记', Decimal('250.00'), None)]>

    ''' 补充:用 ,分割是and关系,用 | 分割是or关系,用 ~ 分割是not关系  '''

    res1 = models.Book.objects.filter(Q(price__gt=300), Q(title='狂人日记')).values_list()  # 查询书籍价格不低于300的和标题为狂人日记的书籍
    print(res1)
    # < QuerySet[] >  没有

    res2 = models.Book.objects.filter(~Q(price__gt=300) | Q(title='狂人日记')).values_list()  # 查询书籍价格低于300的和标题或狂人日记的书籍
    print(res2)
    # <QuerySet [(1, '三国经典版', Decimal('300.00'), 2), (4, '红楼经典版', Decimal('202.00'), 4), (5, '狂人日记', Decimal('250.00'), None)]>

ORM查询优化

查询优化

"""
在IT行业 针对数据库 需要尽量做 能不'麻烦'它就不'麻烦'它
"""
# 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)
"""
	ACID
		原子性
			不可分割的最小单位
		一致性
			跟原子性是相辅相成
		隔离性
			事务之间互相不干扰
		持久性
			事务一旦确认永久生效
			
	事务的开始
		start transcation;
	事务的回滚 
		rollback
	事务的确认
		commit
"""

# django中如何开启事务
    from django.db import transaction
    try:
        with transaction.atomic():
            # sql1
            # sql2
            ...
            # 在with代码快内书写的所有orm操作都是属于同一个事务
    except Exception as e:
        print(e)
    print('执行其他操作')

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')