django can we select related a field on a prefetch related model?

后端 未结 2 754
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 08:19

Assuming these as django model for the sake of simplcity:

class A():

    a = manytomany(\'B\')

class B():

    b = charfield()
    z = foreignkey(\'C\')

class         


        
相关标签:
2条回答
  • 2021-01-31 09:12

    You only need one prefetch_related call:

    foo = A.objects.prefetch_related('a__z').get(pk=1)
    

    This will prefetch both tables. In Django 1.7+ you can improve performance by using a Prefetch object, as in koniiiik's answer.

    0 讨论(0)
  • 2021-01-31 09:13

    This answer is correct with versions of Django prior to 1.7. It produces three queries: first, fetch the instance of A, then fetch its related instances of B and finally fetch the instances of C related to those of B fetched in the second query.

    Before Django 1.7, this is the best you can do, even though the second query could, in theory, select all B objects together with the related C objects joined through the z ForeignKey.

    Starting with Django 1.7, there's a more advanced django.db.models.Prefetch class which allows you to do just that. With Prefetch you can customize the queryset used to prefetch related objects like this:

    foo = A.objects.prefetch_related(
        Prefetch('a', queryset=B.objects.select_related('z'))
    ).get(pk=1)
    

    This results in only two queries (as opposed to three when using prefetch_related('a__z')) and lets the database take care of the second join, which should in theory result in slightly better performance.

    0 讨论(0)
提交回复
热议问题