python购物车数量增加测试脚本语言_如何使用django添加产品数量和更新购物车中的总数量?...

该博客讨论了在Django中实现购物车功能,包括购物车模型和信号处理。作者希望添加商品数量字段,以便用户能指定每件商品的数量,并在添加商品后更新购物车总价。目前的代码只允许一次添加一个商品,而没有处理商品数量。解决方案可能涉及在购物车模型中添加一个`quantity`字段,并相应地更新信号处理函数以计算总价格。
摘要由CSDN通过智能技术生成

我有购物车型号和产品型号

这段代码可以很好地将每个产品一次添加到购物车中,但我想能够添加一个产品的数量,并在添加后更新总数量,但我不确定我应该在哪里添加数量字段有什么想法吗?

我的推车型号: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

有什么办法吗

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值