我需要编写custome create
方法来进行嵌套序列化,所以我要这样做:
def create(self, validated_data):
images = validated_data['commodity']['images']
del validated_data['commodity']['images']
commodity = Commodity.objects.create(**validated_data['commodity'])
del validated_data['commodity']
for image in images:
CommodityImage.objects.create(commodity=commodity, **image)
sizes = validated_data['outwear']['sizes']
del validated_data['outwear']['sizes']
clother = Clother.objects.create(commodity=commodity, **validated_data)
outwear = Outwear.objects.create(clother=clother, **validated_data['outwear'])
for size in sizes:
outwear.sizes.add(size)
return clother
大多数执行良好和磨损实例的线会创建,但是无法添加尺寸到磨损实例,该实例在模型中具有sizes
作为ManyToMany
字段,最后我得到KeyError'sizes'与没有说明。
我究竟做错了什么?谢谢!
已添加:
def create(self, validated_data):
images = validated_data['commodity']['images']
del validated_data['commodity']['images']
commodity = Commodity.objects.create(**validated_data['commodity'])
del validated_data['commodity']
for image in images:
CommodityImage.objects.create(commodity=commodity, **image)
sizes = validated_data['outwear']['sizes']
# del validated_data['outwear']['sizes']
clother = Clother.objects.create(commodity=commodity, **validated_data)
outwear_type = validated_data['outwear']['outwear_type']
name = validated_data['outwear']['name']
outwear = Outwear.objects.create(clother=clother, outwear_type=outwear_type, name=name)
for size in sizes:
outwear.sizes.add(size)
return clother
这解决了问题。看起来很奇怪,因为如果我尝试再次删除尺寸-我会遇到相同的“尺寸”问题。我也有一个:
def __str__(self):
return str(self.size)
作为我的尺寸方法(DecimalField)。
答案 0 :(得分:0)
KeyError'sizes'在此行
sizes = validated_data['outwear']['sizes']
检查validated_data,也许您需要查看尺码是否在外套中?