简体   繁体   English

Django prefetch_related从具有多个ManyToMany关系的模型

[英]Django prefetch_related From Model With Multiple ManyToMany Relationships

Say I have a few models in Django: 假设我在Django中有一些模型:

class Foo(models.Model):
bars = models.ManyToManyField(Bar)
bazs = models.ManyToManyField(Baz)

class Bar(models.Model):
quxs = models.ManyToManyField(Qux)

I can use prefetch_related to get all Bars belonging to Foo and all Quxs belonging to Bar with: 我可以使用prefetch_related来获取属于Foo的所有Bars和属于Bar的所有Qux:

Foo.objects.prefetch_related('bars__quxs')

But how can I use prefetch_related to get this information as well as all the Bazs belonging to Foo? 但是,如何使用prefetch_related来获取此信息以及属于Foo的所有Baz? Would something like: 会是这样的:

Foo.objects.prefetch_related('bars__quxs', 'bazs')

work? 工作?

Yes. 是。 You can pass in multiple lookups to .prefetch_related() 您可以将多个查找传递给.prefetch_related()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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