【发布时间】: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