Skip to content
Advertisement

Django rest framework serializing many to many field

How do I serialize a many-to-many field into list of something, and return them through rest framework? In my example below, I try to return the post together with a list of tags associated with it.

models.py

JavaScript

serializers.py

JavaScript

views.py

JavaScript

Advertisement

Answer

You will need a TagSerializer, whose class Meta has model = Tag. After TagSerializer is created, modify the PostSerializer with many=True for a ManyToManyField relation:

JavaScript

Answer is for DRF 3

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement