使用通用关系进行高效查询
这些是我的模型:
class Comment(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(_('object ID'))
content_object = generic.GenericForeignKey()
user = models.ForeignKey(User)
comment = models.TextField(_('comment'))
class Post(models.Model):
title = models.CharField(_('name'), max_length=80)
creator = models.ForeignKey(User, related_name="created_posts")
created = models.DateTimeField(_('created'), default=datetime.now)
body = models.TextField(_('body'), null=True, blank=True)
现在在我的views.py中,我收到了一篇带有以下说明的帖子:
post = get_object_or_404(Post, id=id)
此时在我的views.py中,获取该帖子的所有评论的最有效的查询(使用ORM)是什么?
These are my models:
class Comment(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(_('object ID'))
content_object = generic.GenericForeignKey()
user = models.ForeignKey(User)
comment = models.TextField(_('comment'))
class Post(models.Model):
title = models.CharField(_('name'), max_length=80)
creator = models.ForeignKey(User, related_name="created_posts")
created = models.DateTimeField(_('created'), default=datetime.now)
body = models.TextField(_('body'), null=True, blank=True)
Now in my views.py I get a post with this istruction:
post = get_object_or_404(Post, id=id)
At this point in my views.py, what is the most efficient query ( with ORM ) to get all comments of that post ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该在帖子上定义comments = generic.GenericRelation(Comment),以便您可以轻松地从帖子访问到评论。一旦完成,这就是一个简单的向后关系:
请注意,这并不是真正的效率问题。通过向后通用关系获取所有相关项目始终最多会产生两个查询 - 一个查询获取相关的 ContentType(在第一次查找时自动缓存),另一个查询获取实际项目。
如果您询问如何尽可能有效地获取多个帖子的所有评论,我会指出您 我的博客有一个很好的技术,但既然你没有,我不会,因为那只是博客嫖娼。
You should define
comments = generic.GenericRelation(Comment)
on the Post, to give you easy access from Post to Comment. Once you've done that, it's a simple backwards relationship:Note that this isn't really a question of efficiency. Getting all the related items via a backwards generic relationship will always incur at most two queries - one to get the relevant ContentType, which is automatically cached on first look-up, and once to get the actual items.
If you had asked how to get all the comments for multiple posts as efficiently as possible, I'd point you to my blog for a good technique, but since you haven't I won't because that would just be blog-whoring.