[Django]-Django: group items by foreign key

4👍

We can .annotate(…) [Django-doc] with the criteria on which we want to order by. We can for example refer to Coalesce(…) with pid, and the case when … then … else … end with type:

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

Leave a comment