class AddCartItemSerializer(serializers.ModelSerializer): product_id = serializers.IntegerField() def validate_product_id(self, value): if not Product.objects.filter(pk=value).exists(): raise serializers.ValidationError('No product with the given ID was found.') return value def save(self, **kwargs): cart_id = self.context['cart_id'] product_id = self.validated_data['product_id'] quantity = self.validated_data['quantity'] try: cart_item = CartItem.objects.get(cart_id=cart_id, product_id=product_id) cart_item.quantity += quantity cart_item.save() self.instance = cart_item except CartItem.DoesNotExist: self.instance = CartItem.objects.create(cart_id=cart_id, **self.validated_data) return self.instance class Meta: model = CartItem fields = ['id', 'product_id', 'quantity'] class UpdateCartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = ['quantity'] xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx class CartItemViewSet(ModelViewSet): http_method_names = ['get', 'post', 'patch', 'delete'] def get_serializer_class(self): if self.request.method == 'POST': return AddCartItemSerializer elif self.request.method == 'PATCH': return UpdateCartItemSerializer return CartItemSerializer def get_serializer_context(self): return {'cart_id': self.kwargs['cart_pk']} def get_queryset(self): return CartItem.objects \ .filter(cart_id=self.kwargs['cart_pk']) \ .select_related('product')