[Python] Django rest framework serializing many to many field

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    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

    Continue reading...

Compartilhe esta Página