如何在预取模型上进行select_related?

时间:2018-07-03 18:25:14

标签: django

是否有可能选择与您预取的模型的外键相关的模型?

一组模型示例:

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

这很有意义,因为发布者和book__publisher都没有与初始模型(作者)相关联。但是我不确定如何指示我要对预取模型(书)而不是起始模型(作者)执行select_related。

我确实看过Prefetch objects,但看不到它们有什么帮助。

1 个答案:

答案 0 :(得分:2)

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

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