带有ManyToManyField的Django REST Framework列

时间:2018-05-04 07:53:11

标签: django django-rest-framework

如何序列化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'])

有更好的方法吗?

1 个答案:

答案 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__'