[Django]-Django-model: Save computed value in a model field

16👍

We should override save() method.

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)
  

25👍

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)

Here is what editable option does. More.

👤f43d65

2👍

Firstly, you must have your ‘computed’ field defined in your TestModel. Then when you are creating a new TestModel record, you can compute x + y during record creation and save it.

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

This should do it.

Leave a comment