2016-06-10 22 views
0

我試圖找到其在同一時間用下面的代碼有兩個標籤中記錄:篩選記錄,並請求與Django的taggits

values = s.split(',') 

query = Q() 

for item in values: 
    query &= Q(tags__name__iexact=item.strip()) 

photos = Photo.objects.filter(query).distinct(); 

它返回空查詢集。 Django的taggit文檔這個例子只提供

Food.objects.filter(tags__name__in=["delicious"]) 

其中在同一時間返回包含任何標籤中的所有記錄,但不能同時

UPD

這是我如何做在我的代碼與「過濾器鏈」。

photos = Photo.objects 
for value in values: 
    photos = photos.filter(tags__name__icontains=value.strip()) 

這實際上意味着

photos.filter(...).filter(...).filter(...)... 

這可能是superslow,但對我的作品。

+0

你可以張貼的照片查詢('打印(photos.query)' )? –

+0

@ElwinArens在這裏是一個例子:http://pastebin.com/3PFivTqr – Mee

回答

0

我不知道這是否是做的最好的方式,但它絕對是一個容易:-)

values = s.split(',') 
sets = []; 

# first get a list of sets of photos containing one tag at a time 
for tag in values: 
    sets.append(set(Photo.objects.filter(tags__name__in=[tag]))) 

# now intersect all sets to get only photos with all tags 
photos = set.intersection(*sets) 
+0

我不太確定它不是超級慢,特別是對於大的請求。這就是我最後的做法(添加到原始文章) – Mee

+0

嗯,對於大量的值來說,它肯定會變得非常慢,因爲它會觸發每個數據庫的數據庫。鏈接過濾器絕對是一種更好的方式,因爲生成的SQL只會觸及數據庫一次......並可能以AND語句結束,這正是您真正想要的。感謝分享。 – andzep

+0

...你應該把你的更新代碼作爲答案,因爲這是你的問題的一個很好的答案。 – andzep