My view method accept values and call score methods, but my terminal output this error >
return sum(item['quantity'] for item in self.cart.values())
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
views.py
def cart_update(request):
cart = Cart(request)
quantity = request.GET.get('quantity')
product_slug = request.GET.get('product_slug')
product = Product.objects.get(slug=product_slug)
cart.add(product=product, quantity=quantity, update_quantity=True)
return JsonResponse({ # here errors
'cart_length':cart.get_length(),
'cart_total':cart.get_total_price(),
'cart_price':cart.get_price(product=product, quantity=quantity)
})
cart.py
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
def get_price(self, product, quantity):
return quantity * Decimal(product.price)
def get_length(self):
return sum(item['quantity'] for item in self.cart.values())
What I am doing wrong?
Behind the curtains, the sum(..)
will call the +
operator to calculate the sum of the items.
If one of the item['quantity']
s is None
, then of course a situation unfolds where you add an int
with None
, hence the error.
You can fix it, by filtering for None
(and zero for example) with:
sum( (item['quantity'] for item in self.cart.values()))
Although it is probably beneficial to look why there is a None
in of these dictionaries, and thus prevent that the dictionaries are "contaminated" by None
s.
self.cart.values()
has some elements in which quantity is None
You can sum only items wich don't have a None
quantity using an if
statement
return sum(item['quantity'] for item in self.cart.values() if item['quantity'])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.