[英]Django: filter foreign keys
我有以下代碼:
query = Entry.objects.all()
print 'authors ' + repr([x.id for x in authors])
print 'query ' + repr(query)
print 'query ids ' + repr([x.author.id for x in query])
query.filter(author__in=authors)
print 'filtered ids ' + repr([x.author.id for x in query])
輸出以下內容:
authors [2]
query [<Entry: test>, <Entry: test>]
query ids [2, 3]
filtered ids [2, 3]
顯然,[2]中沒有3。 那么,為什么過濾的ID是[2,3]而不是[2]?
問候
當您調用query.filter(author__in=authors)
,它將返回一個新的查詢集。 它不會修改現有的查詢集。
如果將新的查詢集分配給查詢,那么您將獲得期望的結果。
query = query.filter(author__in=authors)
print 'filtered ids ' + repr([x.author.id for x in query])
試試這個代替您當前的過濾器:
query = query.filter(author__in=authors)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.