我正在尝试合并客户购物车(会话购物车)项目和现有的用户购物车。如果购物车项目重复增加其他数量,创建一个新的购物车项目。
在我的例子中,用户已经有了一个购物车。在它的三个产品,的简史,的四十条规则
然后用户注销并添加一些产品,
但是我的代码结果总是在购物车中重复产品?
def user_login(request):
if request.user.is_authenticated :
return redirect('home')
else:
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user= authenticate(email =email, password = password)
if user is not None:
try:
cart = Cart.objects.get(cart_id = _cart_id(request))
is_cart_item_exists = CartItem.objects.filter(cart=cart).exists()
if is_cart_item_exists:
cart_items = CartItem.objects.filter(cart=cart)
new_cart_items = []
for cart_item in cart_items:
item = cart_item
new_cart_items.append(item)
print(new_cart_items)
cart_items = CartItem.objects.filter(user=user)
existing_cart_items = []
id =[]
for cart_item in cart_items:
item = cart_item
existing_cart_items.append(item)
id.append(cart_item.id)
print(existing_cart_items)
print(id)
for new_cart_item in new_cart_items:
print(new_cart_item)
if new_cart_item in existing_cart_items: #i think this if condition always returns false, even if new_cart_item is in existing_cart_item.
index=existing_cart_items.index(new_cart_item)
item_id=id[index]
item=CartItem.objects.get(id=item_id)
item.quantity += 1
item.user=user
item.save()
print('added to existing items')
else:
cart_items = CartItem.objects.filter(cart=cart)
for cart_item in cart_items:
cart_item.user = user
cart_item.save()
print('added as a new item')
except:
pass
login(request, user)
return redirect('home')
else:
messages.error(request, "Invalid login credentials")
return render(request, 'accounts/login.html')
Cart与CartItem模型
class Cart(models.Model):
cart_id = models.CharField(max_length=255, blank=True)
date_created = models.DateField(auto_now_add=True)
def __str__(self):
return self.cart_id
class CartItem(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True)
product = models.ForeignKey(Products, on_delete=models.CASCADE)
quantity = models.IntegerField()
is_active = models.BooleanField(default=True)
modified_time = models.DateTimeField(auto_now=True)
def item_total(self):
return self.product.price * self.quantity
def __str__(self):
return self.product.name
终端
[<CartItem: The Alchemist>, <CartItem: Sapiens: a Brief History of Human Kind>]
[<CartItem: The Book Thief>, <CartItem: Sapiens: a Brief History of Human Kind>, <CartItem: The Forty Rules of Love>]
[75, 73, 74]
The Alchemist
added as a new item
Sapiens: a Brief History of Human Kind
added as a new item
_cart_id函数
def _cart_id(request):
cart_id = request.session.session_key
if not cart_id:
car_id = request.session.create()
return cart_id
我认为如果上述条件总是返回false,即使new_cart_item在existing_cart_item中。
发布于 2022-09-12 08:33:22
与其逐一检查所有项目,不如在状态块中尝试类似的操作。
from django.db import Count
user_card_qs = CartItem.objects.filter(user=user)
cart_qs = CartItem.objects.filter(cart=cart)
# get the count of products in the cart
cart_products = dict(
cart_qs.values('product')
.annotate(product_count=Count('product'))
.values_list('product', 'product_count')
)
is_updated = False # not sure we need this flag
# filter only existing items. if no items loop won't iterate
for item in user_card_qs.filter(product__in=cart_products.keys()):
item.quantity += cart_products[item.product]
is_updated = True
if is_updated:
# update all the items that exists in the users cart
CardItem.objects.bulk_update(user_card_qs, update_fields=['quantity'])https://stackoverflow.com/questions/73686210
复制相似问题