我尝试在 Django 中编写一个简单的 Shopping-Cart 并具有以下模型:
class Product(models.Model):
name = models.CharField(max_length=256)
serial = models.CharField(max_length=128)
def __str__(self):
return self.name
class Cart(models.Model):
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
products = models.ManyToManyField(Product, blank=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = CartManager()
def __str__(self):
return str(self.id)
class CartEntry(models.Model):
product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
def __str__(self):
return str(self.id)
我将如何检查产品的 CartEntry 是否已经存在,所以当它已经存在时我可以增加数量 +1,或者在它不存在时创建 CartEntry?
我想这样的事情:
def cart_update(request, id):
product_id = id
my_cart_id, my_cart = Cart.objects.get_or_create(user=request.user)
product_obj = Product.objects.get(id=product_id)
product_quantity = "1"
for item in CartEntry.objects.filter(cart=my_cart_id):
#check all products in CartEntry if it already exists
if not item.product.exists():
#Product does not exists yet - creating a CartEntry
CartEntry.objects.create(cart=my_cart_id, product=product_obj, quantity=product_quantity)
else:
#Product does exists - incrementing the quantity
return HttpResponseRedirect(reverse('list-products'))