Django-最佳实践-计算字段值 [英] Django - what is best practice - Calculating field values

查看:212
本文介绍了Django-最佳实践-计算字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django中有一个模型,该模型具有三个字段,这些字段是根据一个字段的值计算的。特别是其中一个字段的值将要求查询另一个表中的记录(我将使用最后十个值的平均值)。

I have a model in Django which has three fields which are calculated based on the value of one field. The value of one of the fields in particular will require records from another table to be queried ( I will be using the average value of the last ten values).

我不确定在模型类中以模型形式在视图中放置此功能的最佳位置是什么?

I am unsure as to where is the best place to put this functionality, in the model class, in a model form, in a view?

任何建议将不胜感激-谢谢

Any advice would be appreciated - thanks

模型看起来像这样:

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)


推荐答案

将模型作为方法(函数)进入模型,此处的文档 https: //docs.djangoproject.com/en/1.8/topics/db/models/#model-methods ,在下面复制其示例

They should go in the model as methods (functions), docs here https://docs.djangoproject.com/en/1.8/topics/db/models/#model-methods, copied their example below

from django.db import models

class Person(models.Model):
  first_name = models.CharField(max_length=50)
  last_name = models.CharField(max_length=50)
  birth_date = models.DateField()

  def baby_boomer_status(self):
    "Returns the person's baby-boomer status."
    import datetime
    if self.birth_date < datetime.date(1945, 8, 1):
        return "Pre-boomer"
    elif self.birth_date < datetime.date(1965, 1, 1):
        return "Baby boomer"
    else:
        return "Post-boomer"

  def _get_full_name(self):
    "Returns the person's full name."
    return '%s %s' % (self.first_name, self.last_name)
  full_name = property(_get_full_name)

这是将业务逻辑放在一个地方的宝贵技术-模型。

"This is a valuable technique for keeping business logic in one place – the model."

这篇关于Django-最佳实践-计算字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆