我正在尝试做一个购物车系统,用户可以将产品添加到购物车中,如果它已经在那里,我会添加其中一个,但我一直得到错误“'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)
1条答案
按热度按时间k97glaaz1#
get_or_create()
返回一个包含对象的元组和一个指示对象是否已创建的布尔值。要解决这个问题,您需要将代码更改为: