1. 程式人生 > 實用技巧 >ORM-多表查

ORM-多表查

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)