我有购物车型号和产品型号
这段代码可以很好地将每个产品一次添加到购物车中,但我想能够添加一个产品的数量,并在添加后更新总数量,但我不确定我应该在哪里添加数量字段有什么想法吗?
我的推车型号:class CartManager(models.Manager):
def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
qs = self.get_queryset().filter(id=cart_id)
if qs.count() == 1:
new_obj = False
cart_obj = qs.first()
else:
cart_obj = Cart.objects.new()
new_obj = True
request.session['cart_id'] = cart_obj.id
return cart_obj, new_obj
def new(self):
return self.model.objects.create()
class Cart(models.Model):
products = models.ManyToManyField(Product, blank=True)
subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
objects = CartManager()
def __str__(self):
return str(self.id)
推车视图.py文件:-在
^{pr2}$
我使用m2m_changed signal更新购物车的小计,然后使用pre_save signal添加固定的运输成本并更新总计def m2m_changed_cart_receiver(sender, instance, action, *args, **kwargs):
if action == 'post_add' or action == 'post_remove' or action == 'post_clear':
products = instance.products.all()
total = 0
for x in products:
total += x.price
if instance.subtotal != total:
instance.subtotal = total
instance.save()
m2m_changed.connect(m2m_changed_cart_receiver, sender=Cart.products.through)
def pre_save_cart_receiver(sender, instance, *args, **kwargs):
if instance.subtotal > 0:
instance.total = instance.subtotal + 50 #shiping cost
else:
instance.total = 0.00
pre_save.connect(pre_save_cart_receiver, sender=Cart)
我想要的是添加数量,并使用这样的信号更新它,但是我不知道我应该在哪里添加这个数量字段,它应该针对购物车中的每一个产品。
示例:-在Cart 1 contains 2 products
product 1 (quantity 2) price of the unit is 50 , total = 50
product 2 (quantity 3) price of the unit is 100 , total = 200
cart total now is 250
I should take the quantity from the user and then multiple it with the unit price then
update the total of the cart
有什么办法吗