我希望覆盖模型的save方法,以便在保存之前进行一些简单的计算,然后保存最终结果。计算示例(来自我的模型):
total_ticket = ticket2 - ticket1
gross_sales = rate * total_ticket
total_tax = tax * total_ticket
虽然我已经能够完成它,但我很想知道是否有其他更简单的方法来实现它。
看看我的models.py,你明白我的意思
class Entry(models.Model):
ticket1 = models.IntegerField()
ticket2 = models.IntegerField()
total_ticket = models.IntegerField(default=0, editable=False)
rate = models.IntegerField(null=True, blank=True)
tax = models.IntegerField(null=True, blank=True)
gross_sales = models.IntegerField(default=0, editable=False)
total_tax = models.IntegerField(default=0, editable=False)
def save(self, *args, **kwargs):
# calculate sum before saving.
self.total_ticket = self.calculate_ticket()
self.gross_sales = self.calculate_gross_sales()
self.total_tax = self.calculate_tax()
super(Entry, self).save(*args, **kwargs)
def calculate_gross_sales(self):
try:
total_ticket = self.total_ticket
rate = self.rate
return total_ticket * rate
except KeyError:
return 0
def calculate_tax(self):
try:
total_ticket = self.total_ticket
tax = self.tax
return total_ticket * tax
except KeyError:
return 0
def calculate_ticket(self):
""" Calculate a numeric value for the model instance. """
try:
ticket1 = self.ticket1
ticket2 = self.ticket2
return ticket2 - ticket1
except KeyError:
return 0
def __str__(self):
return self.show
答案 0 :(得分:0)
正如@karthinkr在评论中所说,你可以使用pre_save
。这是一个例子:
from django.db.models.signals import pre_save
def calculate_things(sender, instance, **kwargs):
# sender => Model
# instance => Object pre saved
...
# Your loginc here
class Entry(models.Model):
...
# Model definition
...
... # You don't need re define save method.
pre_save.connect(calculate_things, sender=Entry)