Django rest框架序列化多对多字段
如何将多对多字段序列化为列表,然后通过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
回答:
你将需要一个TagSerializer
,其class Meta
有model = Tag
。之后TagSerializer
被创建,修改PostSerializer
与many=True
一个ManyToManyField
关系:
class PostSerializer(serializers.ModelSerializer): tag = TagSerializer(read_only=True, many=True)
class Meta:
model = Post
fields = (tag, text,)
以上是 Django rest框架序列化多对多字段 的全部内容, 来源链接: utcz.com/qa/432502.html