Saqib Ali
Saqib Ali

Reputation: 12585

How to add an element of derived data to a Django model?

I have a Django Model as follows:

class myModel(models.Model): 
    a = models.IntegerField() 
    b = models.IntegerField() 

I want to add a models.BooleanField() named c to the myModel class. However the value of c is simply derived from a and b so I don't want it to be stored in the Database.

I want to c to be True if a > b, otherwise False. I want c to reflect the correct/current value even when a and b get modifed. And I want to be able to access c using myModel.c just like I can access a and b.

Is there any way to do this?

Upvotes: 0

Views: 142

Answers (1)

Pavel Anossov
Pavel Anossov

Reputation: 62908

Define a property:

class myModel(models.Model): 
    a = models.IntegerField() 
    b = models.IntegerField() 

    @property
    def c(self):
        return self.a > self.b

Upvotes: 2

Related Questions