如何序列化ManyToMany字段的数据。我在ManyToMany字段中保存数据时遇到问题。但是,我找到了另一种方法,但最好的方法是什么?
/** Models Code **/
class Layer(models.Model):
group = models.ManyToManyField(Group)
title = models.CharField(max_length=50)
enabled = models.BooleanField(default=False)
/** In views.py **/
addrole = Layer.objects.create(title=str(key), enabled=True)
addrole.group.add(self.request.POST['group'])
有更好的方法吗?
答案 0 :(得分:3)
您可以创建GroupSerializer:
class GroupSerializer(serializers.ModelSerializer):
class Meta:
model = models.Group
fields = '__all__'
然后在LayerSerializer
:
class LayerSerializer(serializers.ModelSerializer):
group_set = GroupSerializer(many=True)
class Meta:
model = models.Layer
fields = '__all__'