1👍
✅
You need to change indentation of JsonResponse
cause it ends after first stock
in product_stock
. Also item.save()
and more probably need indentation change. Revise that in clean Python.
def check_cart_content(request,user_id):
cart = CartItem.objects.filter(user=user_id)
for item in cart:
product_stock = ProductStock.objects.filter(product=item.product.id)
for stock in product_stock:
if item.amount > stock.quantity:
item.amount = stock.quantity
product = Product.objects.get(id=item.product.id)
if item.price != product.price:
item.price = product.price
item.save()
return JsonResponse({'success': 'Cart checked'})
You should think of rebuilding model tree, cause ProductStock
with ForeignKey
seems bad solution. It would be better to count in function of Product
, something similar to:
def quantity(self):
return Product.objects.all().count()
because it works dynamically and you don’t need extra objects in database.
Source:stackexchange.com