如何使用Django添加产品数量和更新购物车中的总数量?

2024-09-27 00:20:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

有什么办法吗


Tags: theinstanceselfidobjnew数量models
1条回答
网友
1楼 · 发布于 2024-09-27 00:20:23

好吧,我想出了解决问题的办法,
也许将来会对别人有所帮助

我创建了一个名为CartItem的新模型,其中包含item,item\u cart,quantity

item_cart is to make sure that the CartItem related to the session cart.

然后in-cart model将products字段更新为这样:

  products    = models.ManyToManyField(CartItem, blank=True)

在购物车添加视图中,我从模板中的表单中获取产品标识和数量,该模板有两个输入字段,一个用于数量,另一个用于产品标识:

^{pr2}$

然后单击“添加到购物车”时,我会为该会话购物车创建一个新的购物车项目,如下所示:

cart_obj, new_obj = Cart.objects.new_or_get(request)
product = Product.objects.get(id=product_id)
item = CartItem.objects.create(item=product,item_cart=cart_obj, quantity=quantity)

然后将项目添加到购物车中,如下所示:

cart_obj.products.add(item)

我希望这对任何人都有帮助:)

相关问题 更多 >

    热门问题