一尘不染

Django:prefetch_related()是否遵循反向关系查找?

django

我已经在django 1.4中从主干尝试过prefetch_related(),但无法使其预取反向查找。

我的简化模型(每本书有很多价格):

class Book(models.Model):
    # some fields

class Price(models.Model):
    book = models.ForeignKey(Book)

我视图的查询:

books = Book.objects.prefetch_related('price')

然后,我得到了AttributeError消息:

AttributeError: Cannot find 'price' on Book object, 'price' is an invalid parameter to prefetch_related()

如何使其运作?谢谢。


阅读 789

收藏
2020-04-02

共1个答案

一尘不染

定义一个相关名称:

class Price(models.Model):
    book = models.ForeignKey(Book, related_name='prices')

然后使用它:

books = Book.objects.prefetch_related('prices')
2020-04-02