Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django-model: Save computed value in a model field

I want to save the django model with computed field so that I can apply search on that.

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
like image 992
wrufesh Avatar asked Jun 02 '15 03:06

wrufesh


2 Answers

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.

like image 123
f43d65 Avatar answered Sep 28 '22 03:09

f43d65


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)
  
like image 30
wrufesh Avatar answered Sep 28 '22 04:09

wrufesh