Django-model:在模型字段中保存计算值

时间:2015-06-02 03:51:36

标签: python django django-models

我想用计算字段保存django模型,以便我可以对其进行搜索。

class TestModel(models.Model):
    x = models.CharField(max_length=16)
    z = models.CharField(max_length=16)

    # I want a field like below and also saves in databse
    # computed =  computed()

    def computed(self):
        result = self.x + self.y
        return result

3 个答案:

答案 0 :(得分:7)

class TestModel(models.Model):
    x = models.CharField(max_length=16)
    z = models.CharField(max_length=16)
    computed = models.CharField(max_length=32, editable=False)

    def save(self, *args, **kwargs):
        self.computed = self.x + self.y
        super(TestModel, self).save(*args, **kwargs)

Hereeditable选项的作用。 More

答案 1 :(得分:3)

我们应该覆盖save()方法。

class TestModel(models.Model):
    x = models.CharField(max_length=16)
    z = models.CharField(max_length=16)
    computed =  models.CharField(max_length=32)

    def get_computed(self):
        result = self.x + self.y
        return result

    def save(self, *args. **kwargs):
        self.computed = self.get_computed()
        super(TestModel, self).save(*args, **kwargs)

答案 2 :(得分:0)

首先,您必须拥有计算的' TestModel中定义的字段。然后,当您创建新的TestModel记录时,您可以在创建记录期间计算x + y并保存它。

TestModel.objects.create(x=x_value, y=y_value, computed=(x_value + y_value))

这应该这样做。