Domanda

Say this is my simple models.py

class Order(models.Model):
    quantity = models.IntegerField()
    item_price = models.FloatField()

I'd like to have a function to calculate the total price:

def calc_total(self):
    return self.quantity * self.item_price

Now, how do I create model field total_price so it gets populated automatically in database? I know I can use calc_total method in template but I need this in db also.

È stato utile?

Soluzione

Override the save method in your model to set the value each time the model is saved:

class Order(models.Model):
    quantity = models.IntegerField()
    item_price = models.FloatField()
    total_price = models.FloatField()

    def calc_total(self):
        return self.quantity * self.item_price

    def save(self, *args, **kwargs):
        self.total_price = self.calc_total()
        super(Order, self).save(*args, **kwargs)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top