使用通用关系进行高效查询

发布于 2024-09-02 14:03:51 字数 764 浏览 5 评论 0原文

这些是我的模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

债姬 2024-09-09 14:03:51

您应该在帖子上定义comments = generic.GenericRelation(Comment),以便您可以轻松地从帖子访问到评论。一旦完成,这就是一个简单的向后关系:

comments = post.comments.all()

请注意,这并不是真正的效率问题。通过向后通用关系获取所有相关项目始终最多会产生两个查询 - 一个查询获取相关的 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:

comments = post.comments.all()

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文