基于其他领域的模型领域? [英] Model field based on other fields?

查看:69
本文介绍了基于其他领域的模型领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以有一个基于其他字段的模型字段吗?例如:

Can I have a model field be based on other fields? For example:

class Foo(models.Model):
    x = models.PositiveSmallIntegerField()
    y = models.PositiveSmallIntegerField()
    z = models.PositiveSmallIntegerField()

    score = models.PositiveSmallIntegerField(default=x+y+z)


推荐答案

是的,处理此问题的最佳方法是覆盖保存模型的方法

Yes, the best way to handle this would be to override the save method of the model

class Foo(models.Model):
    x = models.PositiveSmallIntegerField()
    y = models.PositiveSmallIntegerField()
    z = models.PositiveSmallIntegerField()

    score = models.PositiveSmallIntegerField()

    def save(self, *args, **kwargs):
        self.score = self.x + self.y + self.z
        super(Foo, self).save(*args, **kwargs) # Call the "real" save() method.

请确保您已做好必要的验证工作。

Make sure you take care of the necessary validations.

此处的更多信息:官方文档

这篇关于基于其他领域的模型领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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