python - Django - 什么是最佳实践 - 计算字段值

标签 python django

<分区>

我在 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 

关于python - Django - 什么是最佳实践 - 计算字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33483013/

相关文章:

c++ - 使用 Boost-Python 计算 python 中定义的函数的导数

python - np.where 和 if 在 Pandas 中的组合

php - 强制删除 phpmyadmin 和 PHP7.0 子进程错误

django - 引发 ConnectionError(self._error_message(e)) kombu.exceptions.OperationalError : Error 111 connecting to localhost:6379. 连接被拒绝

django - django admin 中的通用多对多关系

python - 日期时间误差范围

python - 如何在 Anaconda (Conda) 环境中跟踪 pip 安装的软件包?

python - 我无法使用 waigtail 显示图像

python - 连接到本地 mysql 数据库时 manage.py 检查失败

python - 由于组太多,Pandas 过滤器执行缓慢