如何通过“ group_by”查询来调整响应

时间:2019-09-03 12:40:09

标签: python django model-view-controller

我想使用对象的类型作为键为端点创建自定义响应对象。

它是django后端

模型形状:

Model.blahblah(
id = uuid
type = 'type1'
value = 'im batman!'
)

视图:

class HedesView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        hedes = Event.objects.all().query
        events.group_by = ["type"]
        evento = QuerySet(query=hedes, model=Hedes)
        return Response(
            {
                "hedes": EventSerializer(evento, many=True).data 
            }
        )

响应:

    hedes: [{...}, {...}, {...}]

我如何编辑此回复,使其像这样

hedes: {
   type1: [{...}, {...}],
   type2: [{...}]
}

2 个答案:

答案 0 :(得分:1)

我对Django中的group_by语句不是很熟悉,但是在SQL(基础查询语言)中,GROUP BY针对每种类型返回一项,这不是您想要的。

要获得所需的结果,您可能需要编辑EventSerializer的to_representation函数,该函数在以下问题的答案中概述:Liquidcore

答案 1 :(得分:0)

在Django中,如果要像SQL查询中那样“ group_by”,则需要使用ORM的“值”功能。以下代码块帮助我完成了该主题: https://simpleisbetterthancomplex.com/tutorial/2016/12/06/how-to-create-group-by-queries.html