首页 > 解决方案 > 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)。

标签: djangodjango-rest-framework

解决方案


KeyError 'sizes' 在这一行

sizes = validated_data['outwear']['sizes']

检查验证数据,也许您需要查看尺寸是否在外套中?


推荐阅读