django admin在保存模型时填充字段

时间:2015-09-28 17:05:31

标签: python django django-admin

我有一个模特

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_pricesold_price并保存时,我希望自动计算利润。我怎么能这样做?

1 个答案:

答案 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'