django - Django 序列化 KeyError (Django Rest 框架)
问题描述
我需要编写自定义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)。
解决方案
KeyError 'sizes' 在这一行
sizes = validated_data['outwear']['sizes']
检查验证数据,也许您需要查看尺寸是否在外套中?
推荐阅读
- json - 带有子菜单 Vuejs 和 JSON 的动态菜单
- python - 如何在python中同时运行两个同步进程
- python - PyCharm 没有打开 Pygame 窗口
- c# - 如何识别肉眼看起来相同的两个字符串之间的差异
- powershell - Powershell函数-获取多个值
- jenkins - 引诱报告jenkins setup-无法配置java.io.IOException:无法通过代理隧道
- javascript - 这个脚本有什么问题?
- node.js - NPM 警告缺少安装的软件包?
- selenium - Selenium 不加载重定向页面
- pa11y - pa11y failed to Error: 无法启动 chrome