Django:过滤外键
我有以下代码:
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]
显然,3 不在 [2] 中。那么,为什么过滤后的 id 是 [2, 3] 而不仅仅是 [2]?
问候
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]. So, why filtered ids are [2, 3] and not just [2]?
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您调用
query.filter(author__in=authors)
时,它会返回一个新的查询集。它不会修改现有的查询集。如果您将新的查询集分配给查询,那么您将得到您期望的结果。
When you call
query.filter(author__in=authors)
, it returns a new queryset. It does not modify the existing queryset.If you assign the new queryset to query, then you will get the result you were expecting.
尝试这个而不是当前的过滤器:
Try this instead of your current filter: