Search code examples
djangomodelsave

Sum of object fields in django


I have a "Bet" model, there is a total_amount field. I want that when creating a model object, 'total_amount' is the sum of the fields "rubles", "euros", "dollars". But when i create new object then 'total_amount' is 0

class Bet(models.Model):
    bet_id = models.AutoField(primary_key=True)
    event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='bet_event')
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    euros = models.IntegerField(default=0)
    rubles = models.IntegerField(default=0)
    dollars = models.IntegerField(default=0)
    total_amount = models.IntegerField(default=0)
    max_amount = models.IntegerField(default=0)

    def save(self, *args, **kwargs):
        balance = {'euros', 'rubles', 'dollars'}
        self.total_amount = sum([value for key, value in self.__dict__.items() if key in balance])
        super(Bet, self).save(*args, **kwargs)

Solution

  • Please don't store the sum. This is duplicated data. It makes it harder to maintain consistency. Indeed, if you update dollars for example through a query, it will not update the total_amount.

    You can use a property instead:

    class Bet(models.Model):
        bet_id = models.AutoField(primary_key=True)
        event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name='bet_event')
        user = models.ForeignKey(User, on_delete=models.CASCADE)
        euros = models.IntegerField(default=0)
        rubles = models.IntegerField(default=0)
        dollars = models.IntegerField(default=0)
        max_amount = models.IntegerField(default=0)
    
        @property
        def total_amount(self):
            return self.euros + self.rubles + self.dollars

    That being said, I don't know if summing up amounts makes much sense. Summing up a dollar with a euro does not give us two dollars or two euros, that simply is a euro and a dollar.