1👍
✅
Usually one would use a special field type PrimaryKeyRelatedField
.
You don’t even need to manually declare one, as it can be done automatically by the ModelSerializer
.
class CartItemCreateSerializer(serializers.ModelSerializer):
class Meta:
model = CartItem
fields = ('id', 'product', 'quantity')
def save(self, **kwargs):
cart_id = self.context['cart_id']
product = self.validated_data['product']
cart_item, _ = CartItem.objects.get_or_create(
cart_id=cart_id, product=product)
cart_item.quantity += self.validated_data['quantity']
cart_item.save()
self.instance = cart_item
return self.instance
https://www.django-rest-framework.org/api-guide/relations/#primarykeyrelatedfield
Source:stackexchange.com