Search code examples
djangodjango-modelsdjango-1.7django-queryset

Is it possible to prefetch_related over multiple levels?


I'm just wondering if I have three models:

class A(models.Model:
  b = models.ForeignKeyField('B')
class B(models.Model):
  c = models.ForeignKeyField('C')
class C(models.Model):
  user = models.ForeignKeyField('auth.User')

And I'm in a list view for A:

foo = A.objects.all().prefetch_related('B')

Is there any way to have it prefetch C (and then 'auth.User') as well?

I'm using Django 1.7

Thanks for helping!


Solution

  • You should be able to do A.objects.all().prefetch_related('b__c__user'). This will fetch all of A, then look at all of the distinct B objects referenced in A and fetch those, then do the same for B -> C, then for C -> User. The double underscore operator in the field string says "go through this" -- in this case it designates a path to user via b and c. Note that the "b" and the "c" should be lower case because you're specifying the field name, not the class name.

    Performance-wise you might be happier with select_related over prefetch_related unless you have a specific reason why you don't want to have your database do the joins.