Django-我应该把计算方法放在哪里来设计一个合适的、可维护的项目?
我有一些这样的课程Django-我应该把计算方法放在哪里来设计一个合适的、可维护的项目?,django,django-models,software-design,maintainability,Django,Django Models,Software Design,Maintainability,我有一些这样的课程 class RawMaterial(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) amount = models.IntegerField() raw_materials = models.ManyToManyField(RawMaterial
class RawMaterial(models.Model):
name = models.CharField(max_length=100)
class Product(models.Model):
name = models.CharField(max_length=100)
amount = models.IntegerField()
raw_materials = models.ManyToManyField(RawMaterial, through='MaterialProduct', related_name='products')
class MaterialProduct(models.Model):
raw_material = models.ForeignKey(RawMaterial, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
material_price = models.FloatField()
material_rate = models.FloatField()
我想写一个名为计算总价格
的方法,我的方法将使用产品的金额
和材料产品的材料价格
,材料价格
。
为了设计一个合适的/漂亮的/可维护的项目,我应该在哪里写我的方法?到models.py
或views.py
提前感谢。按照胖模型瘦视图的方法,我建议您将该计算放在models.py
中
它可能是这样的:
class MaterialProduct(models.Model):
# attributes
def calculate_total_price(self):
# perform calculation with
# self.product.amount
# self.material_price
# self.material_rate
return result
您也可以从模板({{object.calculate\u total\u price}}
)调用此方法来显示总价
现在,如果您需要多次调用此方法,就会出现一个问题:如果结果不变,为什么还要再次运行此方法
因此,我会更进一步,将其作为一种财产:
class MaterialProduct(models.Model):
# attributes
@property
def total_price(self):
# perform calculation
return result
或者,如前所述,如果您不希望总价格每隔几秒钟就改变一次,那么您可能会选择:
总价现在可以作为模板中的任何其他字段使用(
{{object.total_price}}
)。如果使用cached_属性
,计算将只执行一次,结果将被缓存。再次调用该属性将从缓存中检索结果,您可以将命中保存到数据库和CPU处理时间。您希望该方法做什么?你会怎么称呼它?结果会是什么?结果会出现在哪里?如果它特定于模型,则在模型上,否则在视图上。通常,如果希望通过模型对象访问,则应该将此类方法写入models.py文件。如果只想计算并返回值,可以将此公式添加到views.py
from django.utils.functional import cached_property
class MaterialProduct(models.Model):
# attributes
@cached_property
def total_price(self):
# perform calculation
return result