我有一个模特
class MyModel(models.Model):
title = models.CharField(max_length=100)
net_price = models.IntegerField(default=0)
sold_price = models.IntegerField(default=0)
profit = models.IntegerField(default=0, blank=True, null=True)
在管理员中,当我提供net_price
和sold_price
并保存时,我希望自动计算利润。我怎么能这样做?
答案 0 :(得分:0)
如果未提供,您可以在模型中添加.clean()
方法来计算profit
的值。
如果管理员未提供该值,则执行此操作将在实例上设置profit
属性。
class MyModel(models.Model):
title = models.CharField(max_length=100)
net_price = models.IntegerField(default=0)
sold_price = models.IntegerField(default=0)
profit = models.IntegerField(default=0, blank=True, null=True)
def clean(self):
if getattr(self, 'profit', None) is None: # check that current instance has 'profit' attribute not set
self.profit = self.sold_price - self.net_price # calculate and assign 'profit'