Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

python - Django Rest Framework regroup queryset by a category

In the current project that i'm working on, i need to regroup (group) a queryset by category and put contents with same category in a list all provided together. I have the following model structure:

class Category(models.Model):
    title = models.CharField(max_length=255)

class Item(models.Model):
   title = models.CharField(max_length=255)
   category = models.ForeignKey(to="Category", verbose_name=_('category'), related_name='items',
                                 on_delete=models.SET_NULL, null=True, blank=True)

I would like the output serialized result to be like:

    {
     "category_title_1":[
        {
          "id": 1,
          "title" : "something",
        },
        {
          "id": 2,
          "title": "something else",
        }
      ],
    "category_title_2": [
      {
       "id": 3,
       "title": "another string",
      }, 
      {
       "id": 4,
       "title": "and yet another title",
      }
    ]
  }  

I know i can always iterate over the queryset and group them manually, i'm wondering if there is a native efficient way to do this.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...