返回实例后的Django KeyError(Serializer)

时间:2017-11-05 17:38:14

标签: django django-rest-framework serializer

即将面临以下问题: 我将Cantonment(家庭)插入我的数据库,地址和住宿(沙发/床......)。一切正常(插入)但在正确插入所有内容之后,所创建对象(cantonment)的返回实例抛出错误:

尝试在序列化程序accomodations上获取字段CantonmentCreateSerializer的值时,

得到了AttributeError。 序列化程序字段可能名称不正确,并且与Cantonment实例上的任何属性或键都不匹配。 最初的例外文字是:' Cantonment'对象没有属性'住宿'

在此示例中使用的查询(使用查询)。

正如我所说插入工作,但返回实例是一个错误。 添加 source =' accomodation_set' 可能会显示正确的输出,但我无法插入任何数据。

有没有办法可以使用不同的序列化程序来返回实例(已创建)。如果您需要更多信息(型号)告诉我:)

感谢您的帮助

class CantonmentCreateSerializer(serializers.ModelSerializer):
    address = AddressSerializer()
    accomodations = AccomodationSerializer(many=True)

    # other profile
    class Meta:
        model = Cantonment
        fields = ('id','user','name', 'description', 'type', 'stay_type', 'geom', 'address', 'accomodations')
        read_only_fields=('id', 'user',)

    def create(self, validated_data):
        with transaction.atomic():
            # Create Cantonment first and link it to the address and all accomodations

            ''' Query used
            {
                "stay_type": 1,
                "address": {
                    "raw_address": "1",
                    "street_number": "2",
                    "route": "3",
                    "city": "4",
                    "postal_code": "5",
                    "state": "6",
                    "state_code": "7",
                    "country": "8",
                    "country_code": "9"
                },
                "type": 1,
                "accomodations": [
                    {"accomodation_option": "2", "available_space": "3"},
                    {"accomodation_option": "4", "available_space": "4"}
                ],
                "description": "test",
                "geom": "POINT(1 2)",
                "name": "123"
            }
            '''

            accomodations_data = validated_data.pop('accomodations')
            address_data = validated_data.pop('address')

            cantonment = Cantonment.objects.create(user = validated_data.get('user'),
                name = validated_data.get('name'),
                description = validated_data.get('description'),
                type = validated_data.get('type'),
                stay_type = validated_data.get('stay_type'),
                geom = validated_data.get('geom'))


            address = Address.objects.create(cantonment = cantonment, **address_data)

            # Run through all accomodations submitted and create one accomodation respective
            for accomodation_data in accomodations_data:
               accomodation = Accomodation.objects.create(cantonment = cantonment, **accomodation_data)

        return cantonment

1 个答案:

答案 0 :(得分:2)

地址和住宿必须是只写的。因为Cantonment Model没有地址和住宿属性。

XIP file