一次选择多个对象的最新评论

发布于 2024-12-11 15:32:48 字数 605 浏览 0 评论 0原文

假设我有一个这样的评论模型:

class Comment(models.Model):
    user = models.ForeignKey(User)
    content = models.CharField(max_length=200)
    create_time = models.DateTimeField(blank=True, default=datetime.datetime.now)

    content_type = models.ForeignKey(ContentType, verbose_name=_('content type'))
    object_id    = models.PositiveIntegerField(_('object id'), db_index=True)
    object       = generic.GenericForeignKey('content_type', 'object_id')

我是否可以在一个查询中为同一 content_type 中的多个对象(例如帖子,给出这些帖子的 id)选择最新的几条评论?

如果可能的话,在一个查询中为这些对象选择最旧的评论和最新的 4 条评论怎么样?

谢谢!

Say I have a Comment Model like this:

class Comment(models.Model):
    user = models.ForeignKey(User)
    content = models.CharField(max_length=200)
    create_time = models.DateTimeField(blank=True, default=datetime.datetime.now)

    content_type = models.ForeignKey(ContentType, verbose_name=_('content type'))
    object_id    = models.PositiveIntegerField(_('object id'), db_index=True)
    object       = generic.GenericForeignKey('content_type', 'object_id')

If it's possible for me to select latest several comments for multiple objects in the same content_type (say Posts, giving ids of those Posts) in one query?

If that's possible, how about select the oldest comment and latest 4 comments for those objects all in one query?

Thx!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

厌倦 2024-12-18 15:32:48

我遇到了 greatest-n-per-group 问题。我不得不使用原始 SQL 来获取结果(常见问题解答中每个问题类别的前 X 个问题)。通过 ORM 没有简单的方法来做到这一点。

这篇文章:使用 SQL 的一个有趣的解决方案
SQL 连接:选择最后一条记录一对多关系

我的解决方案涉及子查询。由于您使用的是通用密钥,因此可能会比较麻烦。

我最终只是回到 ORM,对这个特定视图进行积极的缓存,所以我可能会推荐这样做。保持 SQL 太痛苦了。

Foo.objects.raw('''
    SELECT ...
    FROM foo
    LEFT OUTER JOIN bar
    ON (foo.bar_id = bar.id ) 
    WHERE foo.id
    IN (
        SELECT subquery.id 
        FROM foo subquery 
        WHERE foo.bar_id = subquery.bar_id
        ORDER BY score DESC
        LIMIT %s
        )
    ORDER BY "baz" DESC;''', [5])

I've had trouble with the greatest-n-per-group problem. I had to drop to raw SQL to get my results (top X questions per question category in my FAQ). There's no easy way to do this through the ORM.

This post: uses an interesting solution with SQL
SQL join: selecting the last records in a one-to-many relationship

My solution involved subqueries. Since you're using generic keys, it may involve a little more head scratching.

I ended up just going back to the ORM with aggressive caching on this specific view, so I might recommend that. It's juts too much pain to keep up the SQL.

Foo.objects.raw('''
    SELECT ...
    FROM foo
    LEFT OUTER JOIN bar
    ON (foo.bar_id = bar.id ) 
    WHERE foo.id
    IN (
        SELECT subquery.id 
        FROM foo subquery 
        WHERE foo.bar_id = subquery.bar_id
        ORDER BY score DESC
        LIMIT %s
        )
    ORDER BY "baz" DESC;''', [5])
梦断已成空 2024-12-18 15:32:48

您提到“提供这些帖子的 ID”,但实际上没有定义任何帖子模型(至少在您的问题中)。但是,当您要求获取具有相同 content_type 的所有评论时,我不确定如何需要这些帖子。

以下查询获取与特定主键 (1) 的 ContentType 匹配的所有 Comment 项,按 create_time 对它们进行排序,并选择前 4 个项目:

Comment.objects.filter(content_type__pk=1).order_by('-create_time')[:4]

You mention "giving ids of those Posts", but don't actually have any Post model defined (in your question at least). But, as you're asking to get all comments with the same content_type, I'm not sure how the Posts are needed.

The following query gets all Comment items that match a ContentType with a certain primary key (1), orders them by create_time and selects the first 4 items:

Comment.objects.filter(content_type__pk=1).order_by('-create_time')[:4]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文