【问题标题】:Django: group items by foreign keyDjango:按外键分组项目
【发布时间】:2019-09-06 18:31:20
【问题描述】:

我有评论和发布模型如下

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 的 cmets 并将结果分组。

    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 相当于什么?

【问题讨论】:

    标签: django group-by sql-order-by django-queryset coalesce


    【解决方案1】:

    我们可以.annotate(..) [Django-doc] 使用我们想要订购的标准。例如,我们可以用pid 引用Coalesce(…),用type 引用case when … then … else … end

    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'
    )

    【讨论】:

      猜你喜欢
      • 2012-09-25
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 2023-03-13
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      相关资源
      最近更新 更多