简体   繁体   English

Django:过滤外键

[英]Django: filter foreign keys

I have the following code: 我有以下代码:

        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])

Which outputs this: 输出以下内容:

        authors [2]
        query [<Entry: test>, <Entry: test>]
        query ids [2, 3]
        filtered ids [2, 3]

Obviously, 3 is not in [2]. 显然,[2]中没有3。 So, why filtered ids are [2, 3] and not just [2]? 那么,为什么过滤的ID是[2,3]而不是[2]?

Regards 问候

When you call query.filter(author__in=authors) , it returns a new queryset. 当您调用query.filter(author__in=authors) ,它将返回一个新的查询集。 It does not modify the existing queryset. 它不会修改现有的查询集。

If you assign the new queryset to query, then you will get the result you were expecting. 如果将新的查询集分配给查询,那么您将获得期望的结果。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM