我有购物车型号和产品型号 这段代码可以很好地将每个产品一次添加到购物车中,但我想能够添加一个产品的数量,并在添加后更新总数量,但我不确定我应该在哪里添加数量字段有什么想法吗? 我的推车型号:
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
有什么办法吗
好吧,我想出了解决问题的办法,
也许将来会对别人有所帮助
我创建了一个名为CartItem的新模型,其中包含item,item\u cart,quantity
然后in-cart model将products字段更新为这样:
在购物车添加视图中,我从模板中的表单中获取产品标识和数量,该模板有两个输入字段,一个用于数量,另一个用于产品标识:
^{pr2}$然后单击“添加到购物车”时,我会为该会话购物车创建一个新的购物车项目,如下所示:
然后将项目添加到购物车中,如下所示:
我希望这对任何人都有帮助:)
相关问题 更多 >
编程相关推荐