Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

class post(models.Model):     tag = models.ManyToManyField(Tag)     text = models.CharField(max_length=100) 

serializers.py

class PostSerializer(serializers.ModelSerializer):     class Meta:         model = Post         fields = ("text", "tag"??) 

views.py

class PostViewSet(viewsets.ReadOnlyModelViewSet):     queryset = Post.objects.all()     serializer_class = PostSerializer 
like image 608
kengcc Avatar asked Oct 17 '15 02:10

kengcc


People also ask

How do you serialize ManyToMany fields?

To serialize many to many field with Python Django rest framework, we can add a serializer with many set to True . 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.

What is ManyToMany field in Django?

A ManyToMany field is used when a model needs to reference multiple instances of another model. Use cases include: A user needs to assign multiple categories to a blog post. A user wants to add multiple blog posts to a publication.


1 Answers

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:

class PostSerializer(serializers.ModelSerializer):     tag = TagSerializer(read_only=True, many=True)      class Meta:         model = Post         fields = ('tag', 'text',) 

Answer is for DRF 3

like image 187
Brian Avatar answered Sep 19 '22 11:09

Brian