【问题标题】:Django group by and order byDjango group by 和 order by
【发布时间】:2019-08-24 13:49:45
【问题描述】:

我有以下字段的评论表。这里,第一行表示数据库中的第三条评论属于帖子1。第二和第三行表示第三和第四条cmet属于帖子1,它们也是对第二条评论的回复等等。

id    post_id   comment_id  date
 2     1                     ...
 3     1          2          ...
 4     1          2          ...
 5     1                     ...
 6     1          5          ...

我想通过查询做一个 django 组,这样, 获取帖子 1 的所有 cmets,并按对评论的回复对它们进行分组。所以我希望像这样的团体

group1: comment2: comment3,4
group2: comment5: comment6

组查询也应按日期字段排序。我该怎么做?

【问题讨论】:

    标签: django django-queryset


    【解决方案1】:

    鉴于Comment 的以下声明:

    class Comment(models.Model):
        post = models.ForeignKey('Post', on_delete=models.CASCADE)
        replying_to = models.ForeignKey('self', on_delete=models.SET_NULL)
        date = models.DateField()
        text = models.TextField(default='')
    
    grouped_comments = Comment.objects.all().order_by('replying_to', 'date)
    

    你说过你想要:

    获取帖子 1 的所有 cmets,并根据对评论的回复对它们进行分组

    上面的grouped_comments返回所有你想要分组的cmets。如果您只需要特定帖子的 cmets,那么当然,只需过滤 post(使用您自己的帖子选择标准 - 我在下面硬编码了 id):

    grouped_comments = Comment.objects.filter(post__id=1).order_by('replying_to', 'date)
    

    但是,当你去渲染上面的内容时,我认为你将无法做你想做的事。您正在渲染一棵树,而我不知道如何使用查询集来做到这一点。你可能想看看django-mptt。它有template tags for recursive rendering

    【讨论】:

    • 我会在你的 querset 定义中添加一个 prefetch_related 来加快速度!
    • 所以,基本上这就是我需要的SELECT * from comments order by coalesce(comment_id, id), (case when comment_id is null then 1 else 2 end), id;。在 django 中相当于什么?
    猜你喜欢
    • 2011-06-28
    • 2017-02-06
    • 1970-01-01
    • 2022-01-16
    • 2021-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多