简体   繁体   中英

How can you select_related on a pre-fetched model?

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.

You can pass multiple arguments to prefetch method. Try this:

authors = Author.objects.filter(type=10)
authors = authors.prefetch_related('books', 'books__publisher')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM