聯表查詢(基於雙下劃線的跨表查詢)
阿新 • • 發佈:2022-04-04
# 查詢出版社所有的書籍名字和出版社的名字 #出版社查書 反向 多個 # res = models.Publish.objects.filter(name='東方出版社').values('name','book__title') # print(res) # 所有書查出版社 正向 一個 # res = models.Book.objects.filter().values('title','publish__name') # print(res) # 查書id為1的 出版社 正向 一個 # res = models.Book.objects.filter(pk=1).values('title','publish__name') # print(res) # 查詢書籍主鍵是1的作者的手機號 #正向 書籍查作者 # res = models.Book.objects.filter(pk=1).values('authors__author_detail__phone') # print(res) #反向 作者查收書籍 # res = models.Author.objects.filter(book__id=1).values('author_detail__phone','book__title') # print(res) #查詢辰東的書籍 和手機號 #正向 # res = models.Book.objects.filter(authors__name='辰東').values('title','authors__author_detail__phone') # print(res) #反向 # res = models.Author.objects.filter(name='辰東').values('book__title','author_detail__phone') # print(res) # 查詢辰東和唐家三少的書籍 和手機號 #正向 # res = models.Book.objects.filter(authors__name__in=['辰東','唐家三少']).values('title','authors__author_detail__phone') # print(res) #反向 # res = models.Author.objects.filter(name__in=['辰東','唐家三少']).values('book__title','author_detail__phone') # print(res) #通過手機號來查詢書籍 和作者的名字 #反向 # res = models.AuthorDetail.objects.filter(phone=111).values('author__name','author__book__title') # print(res) #通過書籍找到作者和作者的詳請 # res = models.Book.objects.filter(pk=1).values('authors__name','authors__author_detail__phone','authors__author_detail__addr') # print(res) #通過出版社找到書,作者,作者詳情 #出版社查書 反向 # res = models.Publish.objects.filter(name='東方出版社').values('book__title','book__authors__name','book__authors__author_detail__addr') # print(res) #正向 書查出版社 # 1.查詢書籍主鍵為1的出版社 # book_obj = models.Book.objects.filter(pk=1).first() # # 書查出版社 正向 # res = book_obj.publish # print(res) # print(res.name) # print(res.addr) res = models.Book.objects.filter(title='遮天').first() #是列表套的形式,必須得這樣取 book_title = res.title publish_name = res.publish.name aothor_name = res.authors.all().first().name print(book_title,publish_name,aothor_name) ''' select * from app01_book where app01_book.id in (select book_id from app01_book_authors where app01_book_authors.author_id= (select id from app01_author where app01_author.id = (select id from app01_authordetail where app01_authordetail.phone=111))) slect * from "app01_authordetail" inner join "app01_author" on ("app01_authordetail"."id" = "app01_author"."author_detail_id") inner join "app01_book_authors" on ("app01_author"."id" = "app01_book_authors"."author_id") inner join "app01_book" on ("app01_book_authors"."book_id" = "app01_book"."id") where "app01_authordetail"."phone" = 111 ''' ''' 這裡就不需要在寫all了,查到的資料都會顯示出來 正向查詢和反向查詢還是根據外來鍵欄位在誰那裡來判斷 filter的過濾條件:通過什麼查什麼就過濾誰 通過出版社 找作者,作者的書,作者的詳情 filter的就是出版社 跨表操作直接__就可以跨到關聯過欄位的表上,然後就可以直接__name取欄位 哪怕是出版社只關聯了作者,也還是可以通過作者__書找到書,他們之間有一條關聯的線就可以隨意跨 '''