一、跨表查询
1.# # 正向查找 对象查找
# book_obj = models.Book.objects.get(id=3)
# print(book_obj)
# ret = book_obj.publisher.name
# print(ret)
2.# # 正向查找 字段查找
# ret = models.Book.objects.filter(id=3).values_list("publisher__name")
# print(ret) 3.# # 反向查找 对象查找
# publisher_obj = models.Publisher.objects.get(id=1)
# ret = publisher_obj.books.all().values_list("title")
# print(ret)
4.# # 反向查找 字段查找
# ret = models.Publisher.objects.filter(id=1).values_list("books__title")
# print(ret) # 多对多
# # 查询
author_obj = models.Author.objects.get(id=2)
# print(author_obj.name)
# ret = author_obj.book.all()
# print(ret)
二、对象 多对多 对表与表之间的关系进行操作
1.# create 创建新对象 1、在book中创建一本新书,在book和author的关联表中添加关联操作
# author_obj.book.create(title="孩子", publisher_id=3) 2.# add 必须添加对象 或 id
# book_obj = models.Book.objects.get(id=12)
# author_obj.book.add(book_obj)
# # add 多个
# book_obj = models.Book.objects.filter(id__gt=5, id__lt=8)
# print(book_obj)
# author_obj.book.add(*book_obj)
# author_obj.book.add(12) 3.# # set 必须要是一个可迭代对象
# author_obj.book.set([8, 11])
# author_obj.save() 4.# remove 对象或id
# # 对象
# book_obj = models.Book.objects.get(id=7)
# author_obj.book.remove(book_obj)
# id
# author_obj.book.remove(5) 5.# # clear
# new_author_obj = models.Author.objects.get(id=5)
# new_author_obj.book.clear()
注意: models.类(表).操作(create add remove clear),必须要save()
一对多也有clear和remove方法当时foreginkey必须添加null=True
三、聚合分组查询
1.# 聚合
from django.db.models import Avg, Sum, Max, Min, Count
# ret = models.Book.objects.all().aggregate(price_avg = Avg("price"))
# print(ret)
# ret = models.Book.objects.all().aggregate(min_price=Min("price"))
# print(ret)
# ret = models.Book.objects.all().aggregate(price_max=Max("price"), price_min=Min("price"), price_avg=Avg("price"), price_sum=Sum("price"))
# print(ret) 2.# 分组查询
# 查询每一本书的作者个数
# ret = models.Book.objects.all().annotate(author_num=Count("author"))
# for book in ret:
# print("书名:{},数量:{}".format(book.title, book.author_num))
# 查询作者数量大于1的书
# ret = models.Book.objects.all().annotate(author_num=Count("author")).filter(author_num__gt=1)
# print(ret)
# 查询各个作者出的书的总价格
# ret = models.Author.objects.all().annotate(price_sum=Sum("book__price")).values_list("name", "price_sum")
# print(ret)
# 注意:按字段分组的时候,先获取字段,在分组
一般 annotate(聚合函数)
四、F和Q查询 注意:
# F和Q
1.# 查询出 库存数 大于 卖出数的 所有书(两个字段做比较)
from django.db.models import F
# ret = models.Book.objects.filter(remain__gt=F("sale"))
# print(ret)
注意:F查询字段之间进行比较或加减乘除
models.Book.objects.update(sale=(F("sale")+1)*3)
2.# Q 用于表示或,一般用于filter
格式:(字段)|(字段)
锁
所有匹配的行将被锁定,直到事务结束。这意味着可以通过锁防止数据被其它事务修改。
entries = Entry.objects.select_for_update().filter(author=request.user)
五、原子性操作 # 事物支持原子操作
try:
from django.db import transaction
with transaction.Atomic():
new_publisher = models.Publisher.objects.create(name="星火出版社")
new_book = models.Book.objects.create(
title="笑傲江湖",
price=11.11,
remain=10,
sale=10,
publisher_id=1000
)
except Exception as e:
print(str(e)) # 事物操作不支持原子操作
try:
models.Publisher.objects.create(name="天天出版社")
models.Book.objects.create(
title="小",
price=22.22,
remain=10,
sale=10,
publisher_id=1000
)
except Exception as e:
print(str(e))
Django终端打印SQL语句
# 在settings.py文件中的任意位置
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}
注意:value或value_list里的字段相当于SQL语句select 后面的字段
annotate分类按照前面的字段进行分类