我尝试用Django编写一个简单的购物车,并具有以下模型:
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'))
答案 0 :(得分:0)
我想我明白了
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.product.name)
-
from django.db.models import F
def cart_update(request, id):
product_id = id
my_cart_id, my_cart_created = Cart.objects.get_or_create(user=request.user)
product_obj = Product.objects.get(id=product_id)
product_quantity = "1"
items_in_cart = CartEntry.objects.filter(cart=my_cart_id)
# if no products in cart, add product
if not items_in_cart:
CartEntry.objects.create(cart=my_cart_id, product=product_obj, quantity=product_quantity)
else:
# if product already exists in Cart, increment quantity +1
if CartEntry.objects.filter(cart=my_cart_id).filter(product=product_obj):
CartEntry.objects.filter(cart=my_cart_id, product=product_obj).update(quantity=F('quantity')+1)
else:
# product does not exist in Cart -> add it with quantity 1
CartEntry.objects.create(cart=my_cart_id, product=product_obj, quantity=product_quantity)
return HttpResponseRedirect(reverse('list-products'))
当然,欢迎编辑或其他(更好)解决方案。