【问题标题】:Customize JSON output in Django Rest Framework GET call在 Django Rest Framework GET 调用中自定义 JSON 输出
【发布时间】:2016-09-07 03:55:24
【问题描述】:

我正在尝试从 MySQL 数据库中检索过滤列表。查询本身看起来不错,但返回的 JSON 显示如下:

[
{
    "id": "0038",
    "name": "Jane Doe",
    "total_hrs_per_week": 6,
    "timezone": "America/Los_Angeles"
},
{
    "id": "0039",
    "name": "John Doe",
    "total_hrs_per_week": 10,
    "timezone": "America/Los_Angeles"
}]

当我需要构建的规范需要这个时:

{
"people":[
{
    "id": "0038",
    "name": "Jane Doe",
    "total_hrs_per_week": 6,
    "timezone": "America/Los_Angeles"
},
{
    "id": "0039",
    "name": "John Doe",
    "total_hrs_per_week": 10,
    "timezone": "America/Los_Angeles"
}]}

这是我的序列化程序

class PeopleListSerializer(serializers.ModelSerializer):
    id = serializers.CharField(source='id')
    name =serializers.CharField(source='name')
    total_hrs_per_week = serializers.IntegerField(source='total_hrs_per_week')
    timezone = serializers.CharField(source='timezone')

    class Meta:
        model = models.Person
        fields = ('id','name','total_hrs_per_week','timezone')

知道如何以这种方式包装返回的结果吗?

编辑:

我尝试将其包装在另一个序列化程序中

    class PeopleListWrapperSerializer(serializers.Serializer):
        people = PeopleListSerializer(many=True)

        class Meta:
            fields = ['people']

但这会引发以下错误:

尝试在序列化程序 PeopleListWrapperSerializer 上获取字段 people 的值时出现 AttributeError。 序列化程序字段可能命名不正确,并且与 Person 实例上的任何属性或键都不匹配。 原始异常文本为:“Person”对象没有“people”属性。

【问题讨论】:

  • 尝试不使用字段 = ['people'],无论如何它都会占用该字段。也许它在那里感到困惑。但这只是一个猜测。

标签: python json django django-rest-framework


【解决方案1】:

您可以通过覆盖 list() 方法来做到这一点。

class PeopleListView(ListAPIView):

    def list(self, request, *args, **kwargs):
        # call the original 'list' to get the original response
        response = super(PeopleListView, self).list(request, *args, **kwargs) 

        # customize the response data
        response.data = {"people": response.data} 

        # return response with this custom representation
        return response 

【讨论】:

  • 这可行,但是您知道将任何/所有代码保留在序列化程序类中的解决方案吗?我宁愿不从视图中控制序列化。
  • @L.W.我目前不知道仅使用序列化程序的方法。知道任何此类方法后会更新我的答案。
  • 接受这个作为答案。也找不到任何其他解决方案。
  • 作为一个额外的资源,它可能有助于查看分页类(实际上与上述解决方案中的内容类似)。 django-rest-framework.org/api-guide/pagination
【解决方案2】:

根据您希望传入数据和模型的方式,您可以:

【讨论】:

    猜你喜欢
    • 2020-03-01
    • 2017-10-16
    • 2016-11-28
    • 2015-01-13
    • 2020-04-09
    • 1970-01-01
    • 2019-02-02
    • 2016-12-29
    • 2013-08-03
    相关资源
    最近更新 更多