Is it possible to prefetch across 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 list view for A:
foo = A.objects.all().prefetch_related('B')
Is there a way to get C prefetch (and then 'auth.User')?
I am using Django 1.7
Thanks for the help!
source to share
You can do A.objects.all().prefetch_related('b__c__user')
. This will fetch all A and then go through all the individual objects of B referenced by A and retrieve them, then do the same for B -> C, then for C -> User. The double underscore statement in the field line says "Go through this" - in this case it denotes the path to the user via b and c. Note that "b" and "c" must be lowercase because you are specifying the field name, not the class name.
In terms of performance, you might be happier with select_related
over prefetch_related
unless you have a specific reason why you don't want your database to make connections.
source to share