[Django]-Django Rest Framework regroup queryset by a category

8👍

I don’t believe this is possible using the ORM itself, although as Guybrush mentions, itertools.groupby can be used to achieve this – and in a reasonably elegant way.

from itertools import groupby
from operator import itemgetter
from rest_framework.response import Response

items = Item.objects.values('category__title', 'id', 'title').order_by('category__title')
rows = groupby(items, itemgetter('category__title'))
return Response({c_title: list(items) for c_title, items in rows})

1👍

If your goal is to regroup them in a template, have a look at https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#regroup
Note that you’ll have to sort your objects by category first, as regroup relies on that order to produce correct output.

If your goal is to regroup them in the code (as opposed to templates), you can rely on itertools.groupby (see https://docs.python.org/3/library/itertools.html#itertools.groupby). Again, you’ll need to join and sort your data first.

Leave a comment