小编典典

Django rest框架序列化多对多字段

python

如何将多对多字段序列化为列表,然后通过rest框架返回它们?在下面的示例中,我尝试返回该帖子以及与其关联的标签列表。

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

阅读 186

收藏
2020-12-20

共1个答案

小编典典

您将需要一个TagSerializer,其class Metamodel = Tag。之后TagSerializer被创建,修改PostSerializermany=True一个ManyToManyField关系:

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

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

答案是针对DRF 3

2020-12-20