[Answered ]-How do I add to cart more than one of the same item in the serializer (post)?

1👍

you will need to add a model where you can add the quantity of an item that you can order:

class OrderFood(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
                            on_delete=models.CASCADE) 
    ordered = models.BooleanField(default=False)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return f"{self.quantity} of {self.item.title}"

and then you can add or remove an item (or type of food) to/from the order in the views:

class AddToCartView(APIView):
    def post(self, request, *args, **kwargs):
        item_id = request.data.get('id', None)
        if item_id is None:
            return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST)

        item = get_object_or_404(Item, id=item_id)

        order_item = OrderFood.objects.filter(item=item,user=request.user)

        if order_item.exists():
            order_item = order_item.first()
            order_item.quantity += 1
            order_item.save()
        else:
            order_item = OrderFood.objects.create(item=item,user=request.user)
            order_item.save()

not 100% sure about the code ,you’ll need to verify it, hope that could help

Leave a comment