2013-03-12 38 views
0

例模型Q對象定義Django的查詢集與外鍵

Book: 
id title 
1 test111 
2 test222 
3 test333 
4 test444 

Author: 
book_id name 
1  test111 
1  test222 
2  test222 
2  test333 
3  test111 
3  test333 
4  test111 
4  test333 

我想獲得它的作者名稱中包含「111」和「333」的所有書籍(所以所有書籍至少有兩位作者:第一名111名,第二名333名)

我可以使用鏈式查詢來達到這個目標:

books = Book.objects.filter(author__name__icontains="111").filter(author__name__icontains="333") 

這回兩本書ID:3和4

有沒有辦法通過用品質的對象,以達到上述目標呢?

+1

這裏的模型'Book'沒有一個外鍵模式'Author'。那麼如何使用作者姓名進行篩選? – arulmr 2013-03-12 12:41:54

+0

當在shell上調用Book.objects.filter(author__name__icontains =「111」)時,django使用INNER JOIN調用sql查詢(book.id = author.book_id) – 2013-03-12 12:58:29

回答

2

你可以結合reduce和Q,看The power of django’s Q objects的帖子。

from django.db.models import Q 
import operator 
auths = [ "111", "333" ] 
query = reduce(operator.and_, [ Q(author__name__icontains=x) for x in auths ]) 
books = Book.objects.filter(query) 
0

這是一個動態AUTH列表:

pk_list = qs.values_list('pk', flat=True) # i.e [] or [1, 2, 3] 

if len(pk_list) == 0: 
    Book.objects.none() 

else: 
    q = None 
    for pk in pk_list: 
     if q is None: 
      q = Q(pk=pk) 
     else: 
      q = q | Q(pk=pk) 

    Book.objects.filter(q)