Django序列化KeyError(Django Rest框架)

问题描述 投票:0回答:1

我需要编写自定义qazxsw poi方法来进行嵌套序列化,所以我有这个:

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字段在它的模型,最后我得到KeyError'尺寸'没有描述。我究竟做错了什么?谢谢!

添加:

ManyToMany

这解决了这个问题。看起来很奇怪,因为如果我再次尝试删除尺寸 - 我会得到相同的“尺寸”问题。我也有:

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

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

django django-rest-framework
1个回答
0
投票

KeyError'sizes'在此行中

def __str__(self):
    return str(self.size)

检查validated_data,也许你需要看看尺码是否穿着外套?

© www.soinside.com 2019 - 2024. All rights reserved.