Django rest framework serializer returns list instead of json

I have the following tags and message objects in many ways. What I am trying to return in the mail serializer is to return the tags in the list (using only Tag.name only) instead of json, what is the clean way to do this?

serializers.py

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ('name', 'description', 'date_created', 'created_by')

class PostSerializer(serializers.ModelSerializer):
    tags = TagSerializer(read_only=True, many=True)

    class Meta:
        model = Post
        fields = ('post_id',
                  'post_link',
                  'tags')

Currently, PostSerializer returns tags in json format with all fields, I just want it to return tags: ['tag1', 'tag2', 'tag3'] in the list of strings.

+4
source share
1 answer

One way to do this:

class PostSerializer(serializers.ModelSerializer): 
    tags = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('post_id', 'post_link', 'tags')

    def get_tags(self, post):
        return post.tags.values_list('name', flat=True)

The second way is a property in the Post model:

class Post(models.Model):
    ....

    @property
    def tag_names(self):
        return self.tags.values_list('name', flat=True)


class PostSerializer(serializers.ModelSerializer): 
    tag_names = serializers.ReadOnlyField()

    class Meta:
        model = Post
        fields = ('post_id', 'post_link', 'tag_names')
+4
source

Source: https://habr.com/ru/post/1612110/


All Articles