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:
在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',
)
This is returning:
这是回归:
"tags": [
{"name": "Tag1"},
{"name": "Tag2"}
]
But I want:
但我想要:
"tags": [
"Tag1",
"Tag2"
]
2 个解决方案
#1
3
You can override the to_native() method to return the tag name directly (untested):
您可以覆盖to_native()方法直接返回标记名称(未经测试):
class NodeTagSerializer(serializers.ModelSerializer):
def to_native(self, obj):
return obj.name
#2
2
The answer to this changed in v3. The new way to do it is:
在v3中,这个问题的答案发生了变化。新方法是:
class NodeTagSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
return obj.name
#1
3
You can override the to_native() method to return the tag name directly (untested):
您可以覆盖to_native()方法直接返回标记名称(未经测试):
class NodeTagSerializer(serializers.ModelSerializer):
def to_native(self, obj):
return obj.name
#2
2
The answer to this changed in v3. The new way to do it is:
在v3中,这个问题的答案发生了变化。新方法是:
class NodeTagSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
return obj.name