模型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": [], }这意味着家属没有插入在这里,我尝试为我的家属发送嵌套数据(ManyToManyField)但是,在插入数据时出现上述错误。我们有什么办法可以实现这一目标吗?{ "first_name":"soubhagya", "dependents" : [ { "first_name":"soubhagya" } ]}以上是我使用 post 方法发送的数据。请看一看
1 回答
红颜莎娜
TA贡献1842条经验 获得超12个赞
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
提交
取消