首页 > 解决方案 > 如何在预取的模型上选择相关?

问题描述

是否可以选择作为您正在预取的模型的外键的相关模型?

一组示例模型:

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)

然后是查询:

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

在这两种情况下,我都会收到 FieldError:

Invalid field name(s) given in select_related

这是有道理的,因为 publisher 或 books__publisher 都与起始模型(Authors)无关。但我不确定如何表明我想在预取模型(书籍)而不是起始模型(作者)上执行 select_related。

我确实看过Prefetch objects,但我看不出这些会有什么帮助。

标签: django

解决方案


您可以将多个参数传递给prefetch方法。试试这个:

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

推荐阅读