TypeError with calculated field (Django)

1

TypeError with calculated field

unsupported operand type(s) for *: 'int' and 'NoneType'

error in the return line below

models.py

def get_subtotal(self):
    return self.price_sale * self.quantity

subtotal = property(get_subtotal)

admin.py

class SaleDetailInline(admin.TabularInline):
    list_display = ['product', 'quantity', 'price_sale', 'subtotal']
    readonly_fields = ['subtotal', ]
    model = SaleDetail
    extra = 0

In the view the subtotal works, but not in Admin.

    
asked by anonymous 02.07.2015 / 15:42

1 answer

2

This error is occurring because you are trying to multiply an integer by an empty type.

Example:

>>> price_sale = None
>>> quantity = 2
>>> print price_sale * quantity

Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

You can correct it this way:

def get_subtotal(self):
    try:
        return self.price_sale * self.quantity
    except TypeError:
        return 0

or:

def get_subtotal(self):
    if self.price_sale and self.quantity:
        return self.price_sale * self.quantity
    else:
        return 0
    
03.07.2015 / 06:50