4

In Django Rest Framework, how do I serialize values to an array of values rather than an array of objects? Here is a sample of my serializer code:

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


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

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

This is returning:

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

But I want:

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

2 回答 2

7

这个问题的答案在 v3 中发生了变化。新的方法是:

class NodeTagSerializer(serializers.ModelSerializer):
  def to_representation(self, obj):
      return obj.name
于 2015-08-12T07:41:40.773 回答
4

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

class NodeTagSerializer(serializers.ModelSerializer):
    def to_native(self, obj):
        return obj.name
于 2013-11-06T01:22:03.750 回答