Django(七)
聚合查询
'''没有分组也可以使用聚合函数 默认整体就是一组'''
MySQL聚合函数:max\min\sum\count\avg
'''使用时要先导入模块,查询操作时通过.aggregate(聚合函数('字段'))操作'''
eg:
# from django.db.models import Max,Min,Count,Avg,Sum
# # 查询价格最高的书的价格
# res = models.Book.objects.aggregate(Max('price'))
# print(res) # {'price__max': Decimal('80.00')}
# 多重操作(中间逗号隔开)
# res = models.Book.objects.aggregate(Max('price'),Min('price'),Count('pk'),Sum('price'),Avg('price'))
分组查询
mysql分组操作:group by
ORM执行分组操作:如果报错 可能需要去修改sql_mode 移除 only_full_group_by
from django.db.models import Count, Min, Sum
# # 统计每本书的作者个数
# res = models.Book.objects.annotate(author_num=Count('authors__pk')).values('title', 'author_num')
# print(res) # <QuerySet [{'title': 'aaa', 'author_num': 1}, {'title': 'petter100', 'author_num': 1}, {'title': '三国演义', 'author_num': 1}, {'title': '红楼梦', 'author_num': 1}]>
# # 统计每个出版社卖的最便宜的书的价格
# res = models.Publisher.objects.annotate(min_book = Min('book__price')).values('name','min_book')
# print(res) # <QuerySet [{'name': '老男孩出版社', 'min_book': Decimal('50.00')}]>
# # 统计不止一个作者的图书
# res = models.Book.objects.annotate(author_num=Count('authors__id')).filter(author_num__gt=1).values('title','author_num')
# print(res) # <QuerySet []>
# # 统计每个作者出的书的总价格
# res = models.Author.objects.annotate(total = Sum('book__price')).values('name','total')
# print(res) # <QuerySet [{'name': 'petter', 'total': Decimal('250.00')}]>
'''上述查询是以每个表为单位做分组,以字段为单位分组只需在annotate前面加一个values指定字段即可'''
# # 统计每个出版社主键值对应的书籍个数
# res = models.Book.objects.values('publisher__id').annotate(book_num=Count('id')).values('publisher__name','book_num')
# print(res) # <QuerySet [{'publisher__name': '老男孩出版社', 'book_num': 4}]>
F查询
"""
当表中已经有数据的情况下 添加额外的字段 需要指定默认值或者可以为null
方式1
IntegerField(verbose_name='销量',default=1000)
方式2
IntegerField(verbose_name='销量',null=True)
方式3
在迁移命令提示中直接给默认值
"""
from app01 import models
from django.db.models import F, Value
from django.db.models.functions import Concat
# # 查询库存大于销量的书籍
# res = models.Book.objects.filter(stock__gt=F('sales'))
# print(res) # <QuerySet [<Book: 书籍对象bbb>]>
# # 将所有书的价格提升1000块
# models.Book.objects.update(price=F('price')+1000)
# res = models.Book.objects.all().values('price')
# print(res) # <QuerySet [{'price': Decimal('2000.00')}, {'price': Decimal('2000.00')}, {'price': Decimal('2000.00')}]>
# # 将所有书的名称后面加上_爆款后缀
# models.Book.objects.update(title=Concat(F('title'),Value('_爆款')))
# res = models.Book.objects.all()
# print(res) # <QuerySet [<Book: 书籍对象aaa_爆款>, <Book: 书籍对象bbb_爆款>, <Book: 书籍对象ccc_爆款>]>
'''
F查询主要用于查询条件左右两表都需要当前数据的情况
'''
Q查询
from django.db.models import Q
# # 查询价格大于20000或者卖出大于1000的书籍
# res = models.Book.objects.filter(Q(price__gt=20000)|Q(sales__gt=1000)).values('title','price','sales') # '|'代表or,','代表and
# print(res) # <QuerySet [{'title': 'aaa_爆款', 'price': Decimal('200000.00'), 'sales': 200}, {'title': 'bbb_爆款', 'price': Decimal('2000.00'), 'sales': 2000}]>
# # 查询库存不大于1000的书籍
# res = models.Book.objects.filter(~Q(stock__gt=1000)).values('title','stock') # ~就是非的意思
# print(res) # <QuerySet [{'title': 'aaa_爆款', 'stock': 1000}, {'title': 'ccc_爆款', 'stock': 800}]>
'''
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查询优化
"""
在IT行业 针对数据库 需要尽量做 能不'麻烦'它就不'麻烦'它
"""
# 1.orm查询默认都是惰性查询(能不消耗数据库资源就不消耗)
光编写orm语句并不会直接指向SQL语句 只有后续的代码用到了才会执行
# 2.orm查询默认自带分页功能(尽量减轻单次查询数据的压力)
"""前几年django面试经常问"""
# only与defer
only:把查询结果封装成一个个的对象,后面可以通过点的方式取值,不会走数据库查询,如果点击了对象没有的数据
defer:与only相反,对象点括号内出现的字段会走数据库查询,如果点击了括号内没有的字段也可以获取到数据 每次都不会走数据库查询
eg:
res = models.Book.objects.only('title', 'price').first()
print(res.price) # 200000.00
print(res.title) # aaa_爆款
print(res.sales) # 200
# select_related和prefetch_related
select_related:类似于inner join,连接表再查询,所有的结果封装到查询的对象中,后续对象通过正反向查询跨表,内部不会再走数据库查询
prefetch_related:将多次查询之后的结果封装到数据对象中 后续对象通过正反向查询跨表 内部不会再走数据库查询
ORM常见字段
字段 |
功能 |
AutoField() |
定义主键 |
CharField() |
定义字符串 |
IntergerField() |
定义整型 |
DecimalField() |
定义decimal类型 |
DateField() |
定义date日期类型 |
DateTimeField() |
定义datetime日期类型 |
BigIntergerField() |
长整型 |
BooleanField() |
布尔值 |
TextField() |
存储大段文本 |
FileField() |
传文件自动保存到指定位置并存文件路径 |
EmailField() |
存储email |
# 自定义字段类型
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
ORM字段常用参数
参数 |
功能 |
primary_key |
主键 |
max_length |
最大字符长度 |
verbose_name |
字段简介 |
null |
空 |
default |
默认值 |
max_digits |
decimal最大长度 |
decimal_places |
decimal小数点后位数 |
unique |
唯一 |
db_index |
索引 |
auto_now |
表改变自动更新日期 |
auto_now_add |
创建记录添加日期 |
choices |
类似于枚举 |
to |
创建外键指定被关联内容 |
to_field |
创建外键指定被关联内容 |
db_constraint |
是否在数据库中创建外键约束 |
related_name |
修改正向查询的字段名 |
# choices的使用
class User(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
gender_chioce = (
(1,'male'),
(2,'female')
)
gender = models.IntegerField(chioces=gender_chioce)
res = models.User.objects.get('pk=1')
res.get_gender_display() # 'male'
# 如果gender=1,display获取到的就是male
# 如果gender=2,display获取到的就是female
# 如果gender的值不存在,直接返回数值
事务操作
MySQL事务:四大特性(ACID)
原子性
一致性
独立性
持久性
mysql操作:
start transcation; # 开启事务
rollback; # 回滚
commit; # 提交事务
from django.db import transaction
try:
with transaction.atomic():
pass
except Exception:
pass
'''执行完成自动提交,异常后自动回滚'''
ORM执行原生SQL
# 方式一
from django.db import connection, connections
cursor = connection.cursor()
# cursor = connections['default'].cursor()
cursor.execute("""SELECT * from app01_book where id = %s""", [1]) # 条件参数必出放到SQL语句外面,否则报错
res = cursor.fetchone()
print(res) # (1, 'aaa_爆款', 1000, 200, Decimal('200000.00'))
# 方式二
res = models.Book.objects.extra(
select={'newid': 'select count(1) from app01_book where id=%s'},
select_params=[1, ],
)
print(res) # <QuerySet [<Book: 书籍对象aaa_爆款>, <Book: 书籍对象bbb_爆款>, <Book: 书籍对象ccc_爆款>]>
多对多三种创建方式
# 全自动(常见)
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')