模型class Enrollee(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('id')) first_name = models.CharField(max_length=60, verbose_name=_('first name')) dependents = models.ManyToManyField(to=Dependant, blank=True, verbose_name=_('dependents'))class Dependant(TimeStampedModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('id')) first_name = models.CharField(max_length=60, verbose_name=_('first name'))看法class EnrolleeViewSet(viewsets.ModelViewSet): queryset = models.Enrollee.objects.all() serializer_class = serializers.EnrolleeSerializer filter_class = filters.EnrolleeFilter序列化器class EnrolleeSerializer(DynamicFieldsMixin, DynamicFieldsModelSerializer): dependents = DependantSerializer(many=True, required=False) def create(self, validated_data): dependant_data = validated_data.pop('dependents') enrollee = models.Enrollee.objects.create(**validated_data) for dependant in dependant_data: models.Dependant.objects.create(**dependant) return enrolleeclass Meta: model = models.Enrollee fields = '__all__'錯誤: { "first_name": "hmo1", "dependents": [], }這意味著家屬沒有插入在這里,我嘗試為我的家屬發(fā)送嵌套數據(ManyToManyField)但是,在插入數據時出現上述錯誤。我們有什么辦法可以實現這一目標嗎?{ "first_name":"soubhagya", "dependents" : [ { "first_name":"soubhagya" } ]}以上是我使用 post 方法發(fā)送的數據。請看一看
1 回答

紅顏莎娜
TA貢獻1842條經驗 獲得超13個贊
def create(self, validated_data):
dependant_data = validated_data.pop('dependents')
enrollee = models.Enrollee.objects.create(**validated_data)
for dependant in dependant_data:
obj = models.Dependant.objects.create(**dependant)
enrollee.dependents.add(obj)
enrollee.save()
return enrollee
添加回答
舉報
0/150
提交
取消