Setting a default of 0 to IntegerField not working

Viewed 58

In my Django project the user inserts values of items from 1 to 5.

I am trying to add them together so I got at first an error:

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

so I added the default for each IntegerField to be 0, but still receiving the same error.

My question how can I add these classes in Model avoiding this error.

class Info(models.Model):
    item_1_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 1 Amount')

    item_2_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 2 Amount')

    item_3_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 3 Amount')

    item_4_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 4 Amount')

    item_5_amount= models.IntegerField(default=0, null=True, blank=True, verbose_name='Item 5 Amount')

    total_assets= models.IntegerField(null=True, blank=True, verbose_name='Total Assets')

    @property
    def get_total_assets(self):
        return int(self.item_1_amount) + int(self.item_2_amount) + int(self.item_3_amount) + int(self.item_4_amount) + int(self.item_5_amount)

    # @property
    # def get_total_assets(self):
    #     return self.item_1_amount + self.item_2_amount + self.item_3_amount + self.item_4_amount + self.item_5_amount

    def save(self, *args, **kwargs):
        self.total_assets = self.get_total_assets
        super(Info, self).save(*args, **kwargs)
1 Answers

You can make use of or 0 to use 0 in case of a None (or zero):

@property
def get_total_assets(self):
    return (self.item_1_amount or 0) + (self.item_2_amount or 0) + (self.item_3_amount or 0) + (self.item_4_amount or 0) + (self.item_5_amount or 0)

Setting a default=0 will not work for existing records. Furthermore using multiple columns with the same "dimension" (here amounts) is often not a good idea. It might be better to make an Amount model with a ForeignKey to the Info model. In that case you can link zero, one, or more Amounts to an Info model.

Related