Categories
Python Answers

How to serialize many to many field with Python Django rest framework?

Spread the love

Sometimes, we want to serialize many to many field with Python Django rest framework.

In this article, we’ll look at how to serialize many to many field with Python Django rest framework.

How to serialize many to many field with Python Django rest framework?

To serialize many to many field with Python Django rest framework, we can add a serializer with many set to True.

For instance, we write

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

    class Meta:
        model = Post
        fields = ('tag', 'text',)

to create the PostSerializer with the tag field assigned to the TagSerializer instance.

We set many to true to let us serialize many to many fields.

Conclusion

To serialize many to many field with Python Django rest framework, we can add a serializer with many set to True.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *