Reputation: 1881
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.
Upvotes: 7
Views: 9098
Reputation: 129
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
Upvotes: 0
Reputation: 2275
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')
Upvotes: 9