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"
]
The answer to this changed in v3. The new way to do it is:
class NodeTagSerializer(serializers.ModelSerializer):
def to_representation(self, obj):
return obj.name
You can override the to_native() method to return the tag name directly (untested):
class NodeTagSerializer(serializers.ModelSerializer):
def to_native(self, obj):
return obj.name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With