首页 > 解决方案 > 如何实现 django 模型方法

问题描述

我正在尝试构建一个系统,在该系统中我们对数据库中的所有资产进行折旧。资产模型定义如下:

class Asset(models.Model):  
    Asset_description=models.TextField(max_length=100)
    Tag_number=models.TextField(unique=True)
    Asset_Cost=models.IntegerField(default=0)
    Monthly_Depreciation=models.IntegerField(default=0)
    Current_Cost=models.IntegerField(default=0) 

    def __str__(self):
        return self.Asset_description

我如何在模型中实施折旧公式,例如 Monthly_Depreciation=Asset_Cost/3/12Current_Cost=Asset_Cost-Monthly_Depreciation

标签: pythondjangodjango-models

解决方案


首先,您需要区分 python 代码中的计算Monthly_DepreciationCurrent_Cost值,并将它们放在数据库中。

在代码请求中计算它们以添加相应的方法,例如:

class Asset(models.Model):  
    Asset_description=models.TextField(max_length=100)
    Tag_number=models.TextField(unique=True)
    Asset_Cost=models.IntegerField(default=0)
    Monthly_Depreciation=models.IntegerField(default=0)
    Current_Cost=models.IntegerField(default=0) 

    def __str__(self):
        return self.Asset_description

    def get_monthly_deprecation(self):
        return self.Asset_Cost / 3.0 / 12.0

    def get_current_cost(self):
        return self.Asset_Cost - self.Monthly_Depreciation

然后你应该可以给他们打电话:

asset: Asset = ...
monthly_deprecation = asset.get_monthly_deprecation()
current_cost = asset.get_current_cost()

但是,这不会更新数据库中的值。要进行更新,您需要显式更改模型的字段并保存模型。这可以包装到Asset类的方法中:

class Asset(models.Model):
   ...
   def update_costs(self):
       self.Monthly_Depreciation = self.get_monthly_deprecation()
       self.Current_Cost = self.get_current_cost()
       self.save()  # This method will execute the actual UPDATE SQL statement

调用此命令后,update_costs您将更新数据库中的条目:

asset: Asset = ...
asset.update_costs()
# Now both the model and the database should contain
# the calculated values, so you could use them as:
asset.Monthly_Deprecation
asset.Current_Cost

推荐阅读