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

10 views
Skip to first unread message

donarb

unread,
Jan 5, 2013, 12:05:11 PM1/5/13
to django...@googlegroups.com


On Saturday, January 5, 2013 8:48:00 AM UTC-8, Saqib Ali wrote:

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?

Use a property inside your class

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

Now you can access c as myModel.c anytime.

Reply all
Reply to author
Forward
0 new messages