day59
聚合查询
关键字:aggregate
from django.db.models import Max,Min,Count,Sum,Avg
分组查询
关键字:annotate
1.最简单的规律
models后面点什么 就是按什么分组
F与Q查询
from django.db.modles import F,Q
F 能够帮助你获取到表中字段所对应的数据
# 书籍的库存数与卖出数
models.Book.objects.filter(kucun__gt=F('maichu'))
因为filter过滤的条件的都是and连接
modesls.Book.objects.filter(Q(title='python'),Q(price=666))
modesls.Book.objects.filter(Q(title='python')|Q(price=666))
modesls.Book.objects.filter(~Q(title='python')|Q(price=666))
# Q进阶用法
q = Q()
q.connector = 'or'
q.children.append(('title','python'))
q.children.append(('title__icontains','python'))
q.children.append(('price',666))
models.Book.objects.filter(q) # 默认还是and关系
django中如何开启事务
from django.db import transaction
try:
with transaction.atomic():
# 事务操作
except BaseException as e:
print(e)
常见字段及参数
AutoField()
DateField()
DateTimeField()
auto_now
auto_now_add
TextField()
EmailField() varchar(...)
BooleanField() 传布尔值 存0/1
自定义char字段
class MyCharField(models.Field):
def db_type(self,connection):
return 'char(%s)'%self.max_length
orm查询优化
only
defer
select_related
prefetch_related