I have this view I would like to create a cart or update the entries if the cart is already created and if a product is already in the cart then just update its quantity. I am getting an error saying Field id expected a number but got <Cart: John's cart>. Why is the id field even mentioned when I specifically put cart to filter, because I do not have the id of the Entry
class CreateCart(generics.CreateAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = CartSerializer
def post(self, request):
user = User.objects.get(id=request.data.get("user"))
total = request.data.get("carttotal")
usercart = Cart.objects.update_or_create(user=user, cart_total=total)
products = request.data.getlist("products")
for product in products:
obj = json.loads(product)
id = obj.get("id")
qty = obj.get("qty")
product = Product.objects.get(id=id)
exists = Entry.objects.all().filter(cart=usercart, product=product)
if exists:
exists.quantity = qty
else:
Entry.objects.create(product=product, cart=usercart, quantity=qty)
return Response("Items added or updated", status=HTTP_201_CREATED)
This line Django is complaining about:
exists = Entry.objects.all().filter(cart=usercart, product=product)
At first, the update_or_create()
method returns a tuple containing the object and a boolean value indicating whether it was created or updated. So, you should unpack the tuple to get the actual Cart
instance as:
usercart, created = Cart.objects.update_or_create(user=user, cart_total=total)