Typeerror with calculated field (Django)

Asked

Viewed 312 times

1

Typeerror with calculated field

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

error in Return line below

py.models

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 in Admin does not.

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 fix it that 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
  • So what do you suggest: (price_sale * Quantity) or 0 ?

  • @Regisdasilva edited the answer and added the solutions

  • A simple way is to use the or: return self.price_sale * (self.quantify or 0)

  • 1

    @drgarcia1986 se self.price_sale be equal None error will occur, the right is to check both variables and not only the self.quantity.

  • 1

    You’re right, I can’t consider the camp self.price_sale has value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.