Nested writable serializers need your own create()/update().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | # ====================================================================== # Q: Write a serializer for an order with nested items (creation and # validation). # # Nested writable serializers need your own create()/update(). The logic (stock, # prices, transaction) goes in a service, not in the serializer. The price does # not come from the client, the server calculates it. # ====================================================================== class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['product', 'quantity'] class OrderCreateSerializer(serializers.ModelSerializer): items = OrderItemSerializer(many=True) class Meta: model = Order fields = ['id', 'items'] def validate_items(self, items): if not items: raise serializers.ValidationError('Order must have at least one item.') skus = [i['product'].pk for i in items] if len(skus) != len(set(skus)): raise serializers.ValidationError('Duplicate products.') return items def create(self, validated_data): customer = self.context['request'].user.customer return services.place_order(customer, validated_data['items']) # atomic + stock |