0

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?

Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237
9-bits
  • 10,395
  • 21
  • 61
  • 83

2 Answers2

0

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 %}
Timmy O'Mahony
  • 53,000
  • 18
  • 155
  • 177
0

You need to use django-mptt, which will solve this problem for you.

More information on MPTT from wikipedia

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284