Reputation: 1340
Is it possible to select_related models that are foreign keys of a model that you are prefetching?
An example set of models:
class Book(models.Model):
title = models.CharField(max_length=50)
author = models.ForeignKey('Author', related_name='books')
publisher = models.ForeignKey('Publisher')
class Author(models.Model):
name = models.CharField(max_length=50)
type = models.IntegerField() # choices= omitted for brevity
class Publisher(models.Model):
name = models.CharField(max_length=50)
And then the query:
authors = Author.objects.filter(type=10)
authors = authors.prefetch_related('books')
# I tried both of these (but not at the same time):
authors = authors.select_related('publisher') # doesn't work
authors = authors.select_related('books__publisher') # also doesn't work
In both cases, I get a FieldError:
Invalid field name(s) given in select_related
This makes sense, as neither publisher or books__publisher are associated with the starting model (Authors). But I'm not sure how to indicate I want to do a select_related on the prefetched model (Books) instead of the starting model (Author).
I did look at the Prefetch objects, but I couldn't see how those would help.
Upvotes: 0
Views: 29
Reputation: 47364
You can pass multiple arguments to prefetch
method. Try this:
authors = Author.objects.filter(type=10)
authors = authors.prefetch_related('books', 'books__publisher')
Upvotes: 2