我用的是django1.9。我有一个模型,它代表了一个月内医生诊所的病人数量,按年龄和性别分类:
class PracticeList(models.Model):
practice = models.ForeignKey(Practice)
date = models.DateField()
male_0_4 = models.IntegerField()
female_0_4 = models.IntegerField()
male_5_14 = models.IntegerField()
female_5_14 = models.IntegerField()
... etc
total_list_size = models.IntegerField()
prescribing_needs = JSONField(null=True, blank=True)
我使用整数字段的值来驱动根据年龄和性别调整的各种度量。其中有大量不可预测的数据,因此使用JSONField来表示prescribing_needs
。我最初在模型的save
方法中计算并设置了这些:
def save(self, *args, **kwargs):
self.total_list_size = self.male_0_4 + self.female_0_4 + ....
antibiotics = 1.2 * self.male_0_4 + 1.1 * self.female_0_4 + ...
# plus 40-50 other calculations
self.prescribing_needs = {
'antibiotics': antibiotics ...
}
super(PracticeList, self).save(*args, **kwargs)
这是有效的,但使我的模型文件长得难以管理。所以我的问题很简单:什么是Django方法来分割计算save
上所有这些度量的方法?
现在,我只是在models.py
所在的目录中创建了一个名为model_calculations.py
的新文件:
def set_prescribing_needs(c):
antibiotics = 1.1 * c.male_0_4 + 1.1 * female_0_4 ...
prescribing_needs = {
'antibiotics': antibiotics
}
return prescribing_needs
我只是将这个文件导入models.py
并执行以下操作:
def save(self, *args, **kwargs):
self.prescribing_needs = model_calculations.set_prescribing_needs(self)
super(PracticeList, self).save(*args, **kwargs)
这样可以吗,或者有没有更像Djangoish的地方来存储这些方法?你知道吗
这是一个很好的方法,也是Django的方法。我要找两样东西。你知道吗
当您有一些函数在多个应用程序中使用时,请将这些函数放在
main/model_calculations.py
、core/model_calculations.py
或在整个项目中共享的任何应用程序中。你知道吗如果您发现其中一些函数是在模型之外使用的,我会将它们放在
utils.py
文件中。你知道吗只要这些功能只在一个应用程序中使用,并且只在模型中使用,您当前存储它们的地方就可以了。你知道吗
相关问题 更多 >
编程相关推荐