Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'tuple' object has no attribute 'quantity' django

I’m trying to do a cart system where an user can add a product to the cart and if it was already in there I would add one of it but I keep getting the error "’tuple’ object has no attribute ‘quantity’ django".


class OrderItem(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    item = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    cart = models.BooleanField(default=True)
    order = models.BooleanField(default=False)


class Orders(models.Model) :
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    items = models.ManyToManyField(OrderItem)


def add_to_cart(request, pk) :
    item = get_object_or_404(Product, pk=pk)
    order_item = OrderItem.objects.get_or_create(
        item = item,
        user = request.user,
        order = False
    )
    order_qs = Orders.objects.filter(user=request.user)

    if order_qs.exists():
        order = order_qs[0]

        if order.items.filter(item__pk=item.pk).exists() :
            order_item.quantity += 1
            order_item.save()
            return redirect("product-detail", pk = pk)
        else:
            order.items.add(order_item)
            return redirect("product-detail", pk = pk)
    else:
        order = Orders.objects.create(user=request.user)
        order.items.add(order_item)
        return redirect("product-detail", pk = pk)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

get_or_create() returns a tuple containing the object and a boolean indicating whether the object was created or not.

To fix the issue you need to change the code to this:

order_item, created = OrderItem.objects.get_or_create(
    item=item,
    user=request.user,
    order=False
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading