[英]How to use prefetch_related on two M2M values?
I want to prefetch_related
to two level of M2M values,我想
prefetch_related
两个级别的 M2M 值,
Here is my models.py这是我的models.py
class A(models.Model):
name = models.CharField(max_length=40)
b = models.ManyToManyField('B')
class B(models.Model):
name = models.CharField(max_length=40)
c = models.ManyToManyField('C')
class C(models.Model):
name = models.CharField(max_length=40)
d = models.ManyToManyField('D')
And my ORM is我的 ORM 是
a_obj = A.objects.all().prefetch_related('a__b__c')
And I am trying to access the values like below,我正在尝试访问如下值,
Method A:方法一:
for each_obj in a_obj:
print(each_obj.a__b__c)
Method B:方法B:
for each_obj in a_obj:
print(each_obj.a.all())
Method A throws an error saying No such value a__b__b for A found
Method B doesn't throw any error, but the number of queries increases to the length of a_obj.方法 A抛出错误说
No such value a__b__b for A found
方法 B不会抛出任何错误,但是查询的数量会增加到 a_obj 的长度。
Is there a way to access a__b__c
in a single query?有没有办法在单个查询中访问
a__b__c
?
You load both the related B
and C
models with .prefetch_related(…)
[Django-doc] :您使用
.prefetch_related(…)
[Django-doc]加载相关的B
和C
模型:
a_objs = A.objects.prefetch_related('b__c')
But here .prefetch_related(…)
does not change how the items look , it simply loads items.但是这里
.prefetch_related(…)
不会改变项目的外观,它只是加载项目。 You thus can access these with:因此,您可以通过以下方式访问这些:
for a in a_objs:
for b in a.b.all():
for c in b.c.all():
print(f'{a} {b} {c}')
You this still access the items in the same way, but here Django will already load the objects in advance to prevent extra queries.你仍然以同样的方式访问这些项目,但是这里 Django 已经提前加载了对象以防止额外的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.