django - How to bind custom function to model field? -


say simple models.py

class order(models.model):     quantity = models.integerfield()     item_price = models.floatfield() 

i'd have function calculate total price:

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

now, how create model field total_price gets populated automatically in database? know can use calc_total method in template need in db also.

override save method in model set value each time model 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) 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -