3.4.1正向查询与逆向查询的概念:
外键在哪个表,从这个表查另一个表,便是正向查询,反之则是逆向查询。
3.4.2多表查询
3.4.2.1一对一
都是先找类对象,如果是正向:类对象.关系属性(字段=xxx)
如果是逆向:类对象.类名小写(字段=xxx)
# 正向
# author_obj = models.Author.objects.get(a_name='莫言')
# print(author_obj.authorDetail.d_telepho)
# 逆向
detail_obj = models.DetailAuthorInfo.objects.get(d_id=1)
print(detail_obj.author.a_name)
3.4.2.2一对多
# 正向
book_obj = models.Book.objects.get(b_title='人民的名义')
print(book_obj.publish.p_name)
# 逆向,返回Qqueryset类型
publish_obj = models.Publisher.objects.get(p_city='黑龙江省')
print(publish_obj.book_set.all())
4.4.2.3多少多
'''多对多'''
# 正向
book_obj = models.Book.objects.get(b_title='人民的名义')
print(book_obj.authors.all())
# 逆向
author_obj = models.Author.objects.get(a_id=4)
print(author_obj.book_set.all())
3.4.3双下划线查询
3.4.3.1一对一
# 正向
obj = models.Author.objects.filter(a_name='莫言').values('authorDetail__d_addr')
print(obj)
# 逆向
obj = models.DetailAuthorInfo.objects.filter(author__a_name='莫言').values('d_addr')
print(obj)
3.4.3.2一对多
# 正向
obj = models.Book.objects.filter(b_title='人民的名义').values('publish__p_name')
print(obj)
# 逆向
obj = models.Publisher.objects.filter(book__b_title='人民的名义').values('p_name')
print(obj)
3.4.3.3多对多
# 正向
obj = models.Book.objects.filter(b_title__startswith='爸爸').values('authors__a_name')
print(obj)
# 逆向
obj = models.Author.objects.filter(book__b_title__startswith='爸爸').values('a_name')
print(obj)
3.4.3.4进阶(三表/四表操作)
obj = models.Publisher.objects.filter(p_id=4).values('book__authors__authorDetail__d_addr')
print(obj)
obj = models.DetailAuthorInfo.objects.filter(d_addr='陕西省宝鸡市').values('author__book__publish__p_name')
obj = models.Publisher.objects.filter(book__authors__authorDetail__d_addr='陕西省宝鸡市').values('p_name')
obj = models.Book.objects.filter(authors__authorDetail__d_addr='陕西省宝鸡市').values('publish__p_name')
obj = models.Author.objects.filter(authorDetail__d_addr='陕西省宝鸡市').values('book__publish__p_name')
print(obj)