在Django Rest Framework中,如何将值序列化为值数组而不是对象数组?

时间:2013-11-06 01:04:10

标签: django json django-models django-rest-framework

在Django Rest Framework中,如何将值序列化为值数组而不是对象数组?以下是我的序列化代码示例:

class NodeTagSerializer(serializers.ModelSerializer):
    class Meta:
        model = NodeTag
        fields = (
            'name',
        )


class NodeTreeSerializer(serializers.ModelSerializer):
    tags = NodeTagSerializer(required=False)

    class Meta:
        model = NodeTree
        fields = (
            'tags',
        )

这是回归:

"tags": [
    {"name": "Tag1"},
    {"name": "Tag2"}
]

但我想:

"tags": [
    "Tag1",
    "Tag2"
]

2 个答案:

答案 0 :(得分:4)

v3的答案在第3节中有所改变。新方法是:

class NodeTagSerializer(serializers.ModelSerializer):
  def to_representation(self, obj):
      return obj.name

答案 1 :(得分:3)

您可以覆盖to_native()方法直接返回标记名称(未经测试):

class NodeTagSerializer(serializers.ModelSerializer):
    def to_native(self, obj):
        return obj.name