次の問題に直面しています: 住所と宿泊施設(ソファ/ベッド...)を持つ私のデータベースにCantonment(世帯)を挿入します。すべては(挿入)正常に動作しますが、すべてが正しく作成されたオブジェクト(宿営)の返されたインスタンスはエラー投げて挿入された後:シリアライザCantonmentCreateSerializer
上のフィールドaccomodations
の値を取得しようとしたときインスタンスを返す後にDjango KeyError(シリアライザ)
ガットはAttributeErrorを。 シリアライザフィールドの名前が正しくない可能性があり、Cantonment
インスタンスのアトリビュートまたはキーと一致しない可能性があります。 元の例外テキストは、 'Cantonment'オブジェクトに 'accomodations'という属性がありませんでした。
使用されるクエリは、この例(使用されたクエリ)です。
私は挿入が機能していると述べていますが、インスタンスを返すとエラーが発生しています。 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
悲しいことにうまくいきません。 デシリアライズしようとしていますか?いずれにせよ、収容所を返却する際の宿泊施設... – Markus