基于其他领域的模型领域?

时间:2014-03-03 21:06:50

标签: django

我可以将模型字段基于其他字段吗?例如:

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

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

2 个答案:

答案 0 :(得分:6)

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

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.

确保您负责必要的验证。

有关此内容的更多信息:official documentation

答案 1 :(得分:0)

怎么样?

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

     @property
     def score(self):
         return self.x + self.y + self.z

关于模型方法here

的官方文档