Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django Rest Framework, how do I serialize values to an array of values rather than an array of objects?

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"
]
like image 217
Chris Miller Avatar asked Dec 19 '22 21:12

Chris Miller


2 Answers

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
like image 189
MarZab Avatar answered Dec 22 '22 12:12

MarZab


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
like image 22
Lie Ryan Avatar answered Dec 22 '22 11:12

Lie Ryan