[英]Django: How to get related objects of a queryset?
Assume I have two models:假设我有两个模型:
A:
pass
B:
a = foreign_key(A)
Now, I have a query set现在,我有一个查询集
bs = B.objects.filter(...)
I want to get all the a
of bs
, which means every a
which is referenced by b
for which b
is in bs
.我想所有的
a
的bs
,这意味着每a
该被引用b
为其b
是bs
。
Is there a way to do so?有没有办法这样做? I think in sql, a simple join will do, I don't know if django support this.
我认为在sql中,一个简单的join就可以了,我不知道django是否支持这个。
You can use __in
:您可以使用
__in
:
A.objects.filter(b__in=bs)
or you can avoid creating the bs queryset at all, and follow the relation directly in your query:或者您可以完全避免创建 bs 查询集,并直接在查询中遵循关系:
A.objects.filter(b__<bcondition>=<bvalue>)
For example, if the filter used to create bs
was:例如,如果用于创建
bs
的过滤器是:
bs = B.objects.filter(name="Banana")
Then you could filter the A
objects using:然后您可以使用以下方法过滤
A
对象:
A.objects.filter(b__name="Banana")
Bear in mind that there are a number of different ways you can filter, and that the filter functionality is quite extensive, so it is worth reviewing the filter documentation请记住,您可以通过多种不同的方式进行过滤,并且过滤器功能非常广泛,因此值得查看过滤器文档
Extending Daniel's solution, using __in
might return duplicate records if using a related model.扩展 Daniel 的解决方案,如果使用相关模型,则使用
__in
可能会返回重复记录。
For example:例如:
A.objects.filter(b__in=bs).count()
could be more than A.objects.all().count()
A.objects.filter(b__in=bs).count()
可能大于A.objects.all().count()
For me, using distinct()
worked as mentioned in this SO answer对我来说,使用
distinct()
像这个SO answer 中提到的那样工作
A.objects.filter(b__in=bs).distinct()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.