模型
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 enrollee
class Meta:
model = models.Enrollee
fields = '__all__'
错误:
{
"first_name": "hmo1",
"dependents": [],
}
这意味着家属没有插入
在这里,我尝试为我的家属发送嵌套数据(ManyToManyField)但是,在插入数据时出现上述错误。
我们有什么办法可以实现这一目标吗?
{
"first_name":"soubhagya",
"dependents" : [
{
"first_name":"soubhagya"
}
]
}
以上是我使用 post 方法发送的数据。
请看一看
红颜莎娜
相关分类