社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

属于同一类模型的django字段之间的算术运算。有可能吗?

Alberto Sordi • 5 年前 • 2000 次点击  

我需要将django管理模型中的类字段(值)与同一类中的固定值(系数)分开。 此操作的结果应填充同一类的另一个字段(点)。两个值的类型相同(整数)。

例如,用户输入值“180”,然后将系数保留为默认值“10”。当它保存新条目时,它应该出现 Points = 18

所以在我定义的那一刻 'coefficient' Django田野 models.py 默认为10。 如我前面所说,“值”字段是可编辑的。 我想用 F() 但是,要在字段之间执行数学运算,我不确定这是正确的工具还是更简单的工具。 当我在我的模型上设置以下表达式时,当我进行DB迁移时,我会看到很多抱怨。

Points = Visits.objects.all().annotate(div=F('Value') / F('Coefficient'))

因为我是刚来的姜哥人,所以我很感激你帮我,也许我误解了一些显而易见的事情。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/37934
 
2000 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Thomas
Reply   •   1 楼
Thomas    6 年前

您可以简单地覆盖 save() 模型的方法来计算 Points 领域:

    def save(self, *args, **kwargs):
        self.Points = self.Value / self.Coefficient
        super().save(*args, **kwargs)

您可能还需要在这里检查并处理除数为零的问题。

JPG
Reply   •   2 楼
JPG    6 年前

方法1

重写 save() 方法 Value 模型,AS

class Visits(models.Model):
    value = models.IntegerField()
    coefficient = models.IntegerField()
    points = models.IntegerField(blank=True, null=True, editable=False)

    def save(self, *args, **kwargs):
        self.points = int(self.value / self.coefficient)
        super().save(*args, **kwargs)


方法2

使用 @property 装饰者

class Visits(models.Model):
    value = models.IntegerField()
    coefficient = models.IntegerField()

    @property
    def points(self):
        return int(self.value / self.coefficient)