我在 Django 中有一个模型,它具有三个字段,这些字段是根据一个字段的值计算的。特别是其中一个字段的值需要查询另一个表中的记录(我将使用最后十个值的平均值)。
我不确定将此功能放在哪里最好,在模型类中,在模型表单中,在 View 中?
任何建议将不胜感激 - 谢谢
模型看起来像这样:
class slide_library(models.Model):
slide_name = models.Charfield(max_length = 6, primary_key = True)
reference_value = models.FloatField(default= '0')
last_mean = models.FloatField(default= '0')
esd = models.FloatField(default= '0')
criteria = models.Charfield(max_length= 10)
您可以避免使用信号(您应该将信号用作最后的资源),覆盖模型保存方法并在存储实例之前计算您的值。
class slide_library(models.Model):
slide_name = models.Charfield(max_length = 6, primary_key = True)
reference_value = models.FloatField(default= '0')
last_mean = models.FloatField(default= '0')
esd = models.FloatField(default= '0')
criteria = models.Charfield(max_length= 10)
#Overriding
def save(self, *args, **kwargs):
#set here your calculated attributes
self.my_stuff = 'something I want to save in that field'
super(slide_library, self).save(*args, **kwargs)
另外,如果是计算属性,想想如果真的需要存到DB中,可以动态计算。
你可以使用装饰器@cached_property,正如django docs所说
The @cached_property decorator caches the result of a method with a
single self argument as a property. The cached result will persist as
long as the instance does, so if the instance is passed around and the
function subsequently invoked, the cached result will be returned.
Consider a typical case, where a view might need to call a model’s
method to perform some computation, before placing the model instance
into the context
from django.utils.functional import cached_property
class slide_library(models.Model):
slide_name = models.Charfield(max_length = 6, primary_key = True)
reference_value = models.FloatField(default= '0')
last_mean = models.FloatField(default= '0')
esd = models.FloatField(default= '0')
criteria = models.Charfield(max_length= 10)
@cached_property
def derivate_field_1(self):
#Here goes all ur stuff to calculated your field
value = ....your calculated value
return value