【问题标题】:How to shape response with 'group_by' query如何使用“group_by”查询塑造响应
【发布时间】:2019-09-03 12:40:09
【问题描述】:

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

它是一个 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: [{...}]
}

【问题讨论】:

    标签: python django model-view-controller


    【解决方案1】:

    我对 Django 中的 group_by 语句不是很熟悉,但是在底层查询语言 SQL 中,GROUP BY 为每种类型返回一个项目,这不是你想要的。

    要获得您想要的结果,您可能需要编辑 EventSerializer 的 to_representation 函数,此问题的答案中概述了该函数:Django RestFramework group by

    【讨论】:

      【解决方案2】:

      在 Django 中,如果您想像在 SQL 查询中那样“分组”,则需要使用 ORM 的“值”函数。以下块帮助我解决了这个主题: https://simpleisbetterthancomplex.com/tutorial/2016/12/06/how-to-create-group-by-queries.html

      【讨论】:

        猜你喜欢
        • 2020-01-12
        • 2018-03-02
        • 2023-03-03
        • 1970-01-01
        • 2020-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        相关资源
        最近更新 更多