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
You will need a
TagSerializer
, whoseclass Meta
hasmodel = Tag
. AfterTagSerializer
is created, modify thePostSerializer
withmany=True
for aManyToManyField
relation:Answer is for DRF 3
In the serializer on init method you can pass the queryset to the field and rest_framework valide the ids on that queryset
1) first extend your serializer from serializers.ModelSerializer
2) include the field on the meta class
3) in the init method:
You can limit the queryset for that field under any argument using filter or exclude like normally you do. In case that you want include all just use .objects.all()
Django 2.0
For many to many field, if you want specific one:
This works for me.
This is what I did, let´s suppose a Book can have more than one author and an Author can have more than one book: On Model:
On Serializers: