Django:按外键对项目进行分组

Django:按外键对项目进行分组,django,group-by,sql-order-by,django-queryset,coalesce,Django,Group By,Sql Order By,Django Queryset,Coalesce,我有如下评论和帖子模型 class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) parent = models.ForeignKey('self', unique=False, blank=True, null=True, on_delete=models.CASCADE) class Post(models.Model): title = models

我有如下评论和帖子模型

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    parent = models.ForeignKey('self', unique=False, blank=True, null=True, on_delete=models.CASCADE)


class Post(models.Model):
    title = models.CharField(max_length=120, null=False, blank=False)
我使用这个原始sql查询来获取所有具有post_id 11的注释,并对结果进行分组

    all_comments = Comment.objects.raw('SELECT * FROM comments_comment where post_id=11 order by coalesce(parent_id, id), (case when parent_id is null then 1 else 2 end ), created_at')
这个问题对我来说非常有效。但是,我希望以Django方式进行查询,而不是使用原始查询。Django的等价物是什么?

我们可以根据我们想要订购的标准来确定。例如,我们可以参考
将(…)
pid
合并,以及
情况,当…然后…否则…结束
类型

from django.db.models import Case, IntegerField, Value, When
from django.db.models import Coalesce

Comment.objects.filter(
    post_id=11
).annotate(
    pid=Coalesce('parent_id', 'id'),
    type=Case(
        When(parent_id__isnull=True, then=Value(1))
        default=Value(2),
        output_field=IntegerField()
    )
).order_by(
    'pid', 'type', 'created_at'
)