6

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"
]

2 Answers 2

8

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

@user9: care to elaborate? Perhaps in a different question if it's too long?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.