user9690594
user9690594

Reputation:

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' return length

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?

Upvotes: 1

Views: 781

Answers (2)

Amine Messaoudi
Amine Messaoudi

Reputation: 2279

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'])

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476534

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(filter(None, (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 Nones.

Upvotes: 1

Related Questions