Django Rest Framework按类别重新组合查询集 [英] Django Rest Framework regroup queryset by a category

查看:157
本文介绍了Django Rest Framework按类别重新组合查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在从事的当前项目中,我需要按类别对查询集进行重新分组(分组),并将具有相同类别的内容放到一起提供的列表中。
我具有以下模型结构:

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",
      }
    ]
  }  

我知道我总是可以遍历queryset并将它们手动分组,

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.

谢谢

推荐答案

我认为使用ORM本身是不可能的,尽管正如Guybrush所言, itertools.groupby 可用于实现这一目标-且合理

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

这篇关于Django Rest Framework按类别重新组合查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆