Django chaining prefetch_related and select_related

假装没事ソ 提交于 2020-03-02 19:32:26

问题


Let's say I have following models

class Foo(models.Model):
    ...

class Prop(models.Model):
    ...

class Bar(models.Model):
    foo: models.ForeignKey(Foo, related_name='bars', ...)
    prop: models.ForeignKey(Prop, ...)

Now I want to make the following query.

foos = Foo.objects.prefetch_related('bars__prop').all()

Does the above query makes 3 Database calls or only 2 (select_related for prop from bar), given that only one prop is associated with bar

If it takes 3 calls then, is there a way to make it 2 calls by using selected_related for bar -> prop


回答1:


You can use the Prefetch class to specify the queryset that is used in prefetch_related() and this way combine it with select_related():

from django.db.models import Prefetch
bars = Bar.objects.select_related('prop')
foos = Foo.objects.prefetch_related(Prefetch('bars', queryset=bars)).all()

Note that this should be two queries, one for the Foo objects and one for getting the related Bar objects that are being joined in the same query with Prop.



来源:https://stackoverflow.com/questions/54569384/django-chaining-prefetch-related-and-select-related

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!