####################### 基于对象查询(子查询) #######################
#
############## 1.一对多 ##############
# book ------> publisher
#
## 正向查询(正向查询按字段)
# python_obj = models.Book.objects.filter(title="python书籍").first()
# print(python_obj.publisher.name)
#
## 反向查询(反向查询按表名小写_set.all())
# publisher_obj = models.Publisher.objects.filter(name="xx出版社").first()
# for obj in publisher_obj.book_set.all():
# print(obj.title)
#
############## 2.多对多 ##############
# book ------> author
#
## 正向查询
# python_obj = models.Book.objects.filter(title="python书籍").first()
# for obj in python_obj.author.all():
# print(obj.name, obj.age)
#
## 反向查询
# author_obj = models.Author.objects.filter(name="changwoo").first()
# for obj in author_obj.book_set.all():
# print(obj.title)
#
############## 3.一对一 ##############
# author ------> authordetail
#
# 正向查询 查找changwoo的手机号
# changwoo = models.Author.objects.filter(name="changwoo").first()
# print(changwoo.AuthorDetail.telephone)
#
# 反向查询 查找家在北京的作者
# beijing = models.AuthorDetail.objects.filter(addr="beijing").first() # 仅查找第一个家在北京的作者
# print(beijing.Author.name)
# beijing_list = models.AuthorDetail.objects.filter(addr="beijing") # 查找所有家在北京的作者
# for beijing in beijing_list:
# print(beijing.Author.name)
#
#
####################### 基于QuerySet和双下划綫__查询(join查询) #######################
# 正向查询按字段,反向查询按表名
#
# 查询python这本书籍的出版社的邮箱
# select publisher.email from Book left join Publisher on book.publisher_id=publisher.id where book.title="python"
# ret = models.Book.objects.filter(title="python").values("publisher__email") # 方式一
# ret = models.Publisher.objects.filter(book__title="python").values("email") # 方式二
# print(ret.query) # 会打印对应的sql语句
#
# 查询手机号以151开头的作者出版过的书籍名称以及书籍对应的出版社名称
#
# models.Book.objects.filter(book__author__authordetail__startswith="151").values("book.title", "publisher.name")
####################### 聚合与分组 #######################
############## 1.聚合 ##############
# from django.db.models import Sum, Count, Min, Max, Avg
# ret = models.Person.objects.all().aggregate(age_sum=Avg("age")) # aggregate是queryset终止函数 打印出字典类型{'age_avg': 232}
# print(ret)
############## 2.分组 ##############
# 跨表分组查询
# select dept.name,Count(*) form person left join dept on person.dept_id=dept.id group by dept.name
# ret = models.Person.objects.values('dept__name').annotate(c=Count('dept')).values('dept__name', 'c') # annotate返回的是queryset
# print(ret)