Я хочу создать три экземпляра модели, используя только один сериализатор, из одного запроса POST. Мне нужно обновить order, order_info, order_contact Данные, которые я получаю, выглядят так:
{
"longitude": "67.929655",
"latitude": "34.263974",
"amount_from_client": "2600.00",
"address": "New York",
"datetime_client": "2019-08-01 16:31:00",
"city": "New York",
"partner_name": "Partner",
"text": "",
"client_name": "Qwerty",
"client_order_code": 2174206,
"datetime_partner": "2019-08-01 16:31:00",
"amount_to_partner": "2000.00",
"delivery_address_comment": "",
"created": "2019-08-01 16:31:00",
"client_phone": "74789",
"partner_phone": "9988",
"client_id": 6,
}
и вот мои сериализаторы:
class OrderDetailsCreateSerializer(serializers.ModelSerializer):
order_info = OrderInfoSerializer(many=False)
order_contact = OrderContactSerializer(many=False)
client_id = serializers.IntegerField(write_only=True)
class Meta:
model = Order
fields: Tuple = (
'address', 'amount_from_client',
'amount_to_partner', 'client_order_code', 'text',
'order_info', 'order_contact', 'client_id',
)
def create(self, validated_data):
client = Client.objects.get(id=validated_data.pop('client_id'))
order_info = validated_data.pop('order_info', None)
order_contact = validated_data.pop('order_contact', None)
order = Order.objects.create(**validated_data)
OrderInfo.objects.create(**order_info, order=order, client=client)
OrderContact.objects.create(**order_contact, order=order)
return order
class OrderInfoSerializer(serializers.ModelSerializer):
class Meta:
model = OrderInfo
fields: Tuple = (
'datetime_client', 'datetime_partner', 'created',
'client',
)
class OrderContactSerializer(serializers.ModelSerializer):
class Meta:
model = OrderContact
fields: Tuple = (
'client_name', 'client_phone',
'partner_name', 'partner_phone',
)
Для отправки данных в OrderDetailsCreateSerializer мои данные формат должен быть таким:
{
"longitude": "67.929655",
"latitude": "34.263974",
"amount_from_client": "2600.00",
"address": "New York",
"city": "New York",
"text": "",
"client_order_code": 2174206,
"amount_to_partner": "2000.00",
"delivery_address_comment": "",
"client_id": 6,
"order_info": {
"datetime_client": "",
"datetime_partner": "",
"created": ""
},
"order_contact": {
"client_phone": "",
"client_name": "",
"partner_phone": "",
"partner_name": ""
}
}
Есть ли хороший способ переформатировать данные? Или мне нужно изменить его только вручную, например:
data['order_info'] = {'created': data['created']...}
Please help)
How I can deserialize json into this format?