Search code examples
djangodjango-querysetdjango-aggregation

Ordering query objects in django


I'm trying to order the results of my query in a sort of parent/child manner. I'm wondering if there's an easy way to accomplish this.

Object:

Video : [id, parent_id, date]  // where parent_id can be null - meaning it is a 'root' node.

Queryset ordering I want:

Video 1: [123, null, 01/11]
  Video 2: [111, 123, 02/11]
  Video 3: [144, 123, 04/11]

Video 4: [191, null, 03/11]
  Video 5: [118, 191, 03/11]
  Video 6: [121, 191, 05/11]

Video 7: [411, null, 04/11]

...

Is there a way to achieve this sort of parent/ child group ordering in a queryset?


Solution

  • If you need to use this at the template level, you can use the regroup template tag to reorder the queryset:

    https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#regroup

    {% regroup videos by parent_id as group %}
    {% for video in group %}
        {{ video.grouper }}
        {% for child in group.list %}{{ child }}{% endfor %}
    {% endfor %}