Search code examples
pythondjangodjango-modelscalculated-columnscalculated-field

Calculated fieds in python django


I have a Table in my database with fields id, body_temp, and status, and its defined by the following class:

class Temperature(models.Model):
    ...
    id = models.AutoField(primary_key=True)
    body_temp = models.DecimalField(max_digits=3, decimal_places=1)
    status = models.CharField(max_length=20)
    ...

the field body_temp will be populated by means of a form, on the other hand, I want the field status to store a string based on the value entered in the field body_temp. if the temperature value entered in the field body_temp is less than 38, I want the field status to store a string normal. However, if the temperature value entered in the field body_temp is greater or eaqual to 38, I want the field status to store a string suspect. How can I do this?


Solution

  • You can set your status field as a property, then it will be calculated on the fly

    class Temperature(models.Model):
        ...
        id = models.AutoField(primary_key=True)
        body_temp = models.DecimalField(max_digits=3, decimal_places=1)
    
        @property
        def status(self):
            if self.body_temp < 38:
                return 'normal'
            else:
                return 'suspect'
    

    Or you can override save() method to calculate this field on any edit and store result in DB

    class Temperature(models.Model):
        ...
        id = models.AutoField(primary_key=True)
        body_temp = models.DecimalField(max_digits=3, decimal_places=1)
        status = models.CharField(max_length=20)
        ...
    
        def save(self, *args, **kwargs):
            if self.body_temp < 38:
                self.status = 'normal'
            else:
                self.status = 'suspect'
            super().save(*args, **kwargs)