简体   繁体   中英

Django rest framework serializer return a list instead of json

I have the following tags and posts objects in many to many relationship. What I try to return in the post serializer is to return the tags in a list (using Tag.name only) instead of json, what's the clean way of doing 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, the PostSerializer returns tags in json format with all fields, I just want it to return tags: ['tag1', 'tag2', 'tag3'] in a string list.

One way to do this is:

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)

Second way is with a property on 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')

One very simple solution for you might be to change this

tags = TagSerializer(read_only=True, many=True)

into this

tags = TagSerializer(read_only=True, many=True).data

this will list your tags as ids instead of listing all of the attributes of every tag

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM