[英]Django perform a join on multiple tables
I have the following tables,我有以下表格,
class A:
field_1 = models.CharField()
field_2 = models.IntegerField()
class B:
a = models.ForeignKey(A, related_name='table_b')
some_other_field = models.CharField()
class C:
b = models.ForeignKey(B, related_name="table_c")
other_field = models.CharField()
Let's assume ids
are provided for objects on table A
, I need to get all the C
objects that are related to table A
through table B
.假设为表A
上的对象提供了ids
,我需要获取与表A
到表B
相关的所有C
对象。 I have the following query, which gives me what I need but I am wondering if there is a better way to do this, I was reading into prefetch_related
and select_related
but can't wrap my head around on how to use them so far我有以下查询,它为我提供了我需要的东西,但我想知道是否有更好的方法来做到这一点,我正在阅读prefetch_related
和select_related
但到目前为止我还不清楚如何使用它们
c_list = C.objects.filter(b__in=B.objects.filter(a__pk__in=table_a_ids))
Also, I would like to group them by other_field
另外,我想按other_field
对它们进行分组
Any help is much appreciated.任何帮助深表感谢。
No need for .select_related(…)
or .prefetch_related(…)
.不需要.select_related(…)
或.prefetch_related(…)
。 You can filter with:您可以使用以下方式过滤:
c_list = C.objects.filter(b__a_id__in=table_a_ids)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.