Как объединить элемент гостевой корзины и пользовательской корзины Django?
Я пытаюсь объединить элементы гостевой корзины (корзины сессии) и существующей корзины пользователя. если элементы корзины повторяются, увеличьте количество, иначе создайте новый элемент корзины.
В моем случае у пользователя уже есть корзина. в ней три товара [<CartItem: The Book Thief>, <CartItem: Sapiens: a Brief History of Human Kind>, <CartItem: The Forty Rules of Love>]
потом пользователь вышел из системы и добавил несколько товаров [<CartItem: The Alchemist>, <CartItem: Sapiens: a Brief History of Human Kind>]. , то когда он снова входит в систему, повторяющийся товар должен добавить количество, а не как повторяющийся товар. и новый товар должен отображаться как новый товар в корзине.
но результат моего кода всегда повторяет товар в корзине?
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
Я думаю, что условие if в приведенном выше примере всегда возвращает false, даже если новый_товары_карты находится в существующем_товаре_карты.
Вместо того, чтобы проверять все элементы по одному, вы можете попробовать что-то вроде этого в блоке условий
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'])