Django:prefetch_related()是否遵循反向关系查找?
我已经在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()
如何使其运作?谢谢。
回答:
定义一个相关名称:
class Price(models.Model): book = models.ForeignKey(Book, related_name='prices')
然后使用它:
books = Book.objects.prefetch_related('prices')
以上是 Django:prefetch_related()是否遵循反向关系查找? 的全部内容, 来源链接: utcz.com/qa/427809.html