我需要编写自定义的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大多数代码行都做得很好,并且创建了outwear实例,但是in不能将尺寸添加到outwear实例中,它的模型中有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)。
发布于 2018-09-07 23:18:19
KeyError 'sizes‘在这一行
sizes = validated_data['outwear']['sizes']看看validated_data,也许你需要看看尺码是否在外衣中?
https://stackoverflow.com/questions/52225104
复制相似问题