[英]how to add quantity of products and update total in cart using django?
我有購物車 model 和產品 model 這段代碼可以很好地將每個產品一次添加到購物車中,但我希望能夠添加產品的數量並在添加后更新總數,但我不確定應該在哪里添加數量字段有任何想法嗎? 我的購物車 model:-
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)
購物車views.py 文件:-
def cart_home(request):
cart_obj, new_obj = Cart.objects.new_or_get(request)
context = {
'cart': cart_obj,
}
return render(request, "carts/home.html", context)
def cart_update(request):
product_id = request.POST.get('product_id')
if product_id is not None:
try:
item = Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("show message to user, product doesn't exist")
return redirect("carts:cart")
cart_obj, new_obj = Cart.objects.new_or_get(request)
if item in cart_obj.products.all():
cart_obj.products.remove(item)
else:
cart_obj.products.add(item)
return redirect("carts:cart")
我使用 m2m_changed 信號更新購物車的小計,然后使用 pre_save 信號添加固定運費並更新總計
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 的新 model,其中包含 item、item_cart、數量、
item_cart 是為了確保 CartItem 與 session 購物車相關。
然后在購物車 model 更新產品字段如下:
products = models.ManyToManyField(CartItem, blank=True)
在 cart_add 視圖中,我從模板中的表單中獲取 product_id 和數量,該表單有 2 個輸入字段,一個用於數量,一個用於產品 ID 的隱藏字段:
product_id = request.POST.get('product_id')
quantity = request.POST.get('quantity_field')
然后當單擊添加到購物車時,我為此 session 購物車創建一個新的 CartItem,如下所示:
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)
我希望這對任何人都有幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.