Django:prefetch_related() 是否遵循反向关系查找? [英] Django: Does prefetch_related() follow reverse relationship lookup?

查看:24
本文介绍了Django:prefetch_related() 是否遵循反向关系查找?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 django 1.4 中从主干尝试了 prefetch_related() 并且无法预取反向查找.

I've tried prefetch_related() in django 1.4 from trunk and can't make it to prefetch reverse lookup.

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

My simplified models (each book has many prices):

class Book(models.Model):
    # some fields

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

我的视图查询:

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

然后,我收到了 AttributeError 消息:

Then, I got the AttributeError message:

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() 是否遵循反向关系查找?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆