Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 920
kengcc Avatar asked Oct 18 '15 08:10

kengcc


People also ask

What does a serializer return Django?

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.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

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.

What does serializer data return?

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 ).

What is renderers in Django REST Framework?

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.


1 Answers

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')
like image 196
Bogdan Iulian Bursuc Avatar answered Nov 14 '22 22:11

Bogdan Iulian Bursuc