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.
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
The BaseSerializer class caches its data attribute on the object, but Serializer. data returns a copy of BaseSerializer. data every time it is accessed (via ReturnDict ).
The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client. REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With