首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django Serialization KeyError (Django Rest框架)

Django Serialization KeyError (Django Rest框架)
EN

Stack Overflow用户
提问于 2018-09-07 22:55:57
回答 1查看 483关注 0票数 0

我需要编写自定义的create方法来进行嵌套序列化,所以我有以下代码:

代码语言:javascript
复制
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‘。我做错了什么?谢谢!

添加:

代码语言:javascript
复制
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

这就解决了问题。看起来很奇怪,因为如果我再次尝试删除大小-我得到相同的‘大小’的问题。另外,我还有一个:

代码语言:javascript
复制
def __str__(self):
    return str(self.size)

作为我的大小方法(DecimalField)。

EN

回答 1

Stack Overflow用户

发布于 2018-09-07 23:18:19

KeyError 'sizes‘在这一行

代码语言:javascript
复制
sizes = validated_data['outwear']['sizes']

看看validated_data,也许你需要看看尺码是否在外衣中?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52225104

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档