DRF返回json的数据attr内的项而不是数组

时间:2016-03-17 21:14:20

标签: python django django-rest-framework

将端点结果序列化的最佳方法是:

{
  status: 200,
  meta: {
    "name": "foo",
    "total": 666
  },
  data: [
     {item1},
     {item2},
     {item3},
     ...with the pagination affecting this array
  ]
}

默认情况下,我得到:

[
  {item1},
  {item2},
  {item3},
  ...with pagination
]

我能够得到接近我想要的结果(缺少分页),但我相信这不是最好的方法。我的序列化器如下:

class FooSerializer(serializers.ModelSerializer):
  status = serializers.SerializerMethodField()
  meta = serializers.SerializerMethodField()
  data = serializers.SerializerMethodField()

  def get_status(self, obj):
    return status.HTTP_200_OK

  def get_meta(self, obj):
    summary = {
      "name": obj.name,
        "total": obj.user.device_set.count()
    }
    return summary

  def get_data(self, obj):
    devices = obj.user.device_set.all()
    return DeviceListSerializer(devices, many=True).data

  class Meta:
    model = Device
    fields = ('status', 'meta', 'data')

1 个答案:

答案 0 :(得分:0)

它接近你得到的回复......

response_dic = {}
response_dic['status_code'] = status_code
if settings.HTTP_USER_ERROR == status_code:
    response_dic['error'] = response
elif response:
    response_dic['data'] = data
    response_dic['meta'] = meta
return response_dic