How to make a Django model fields calculated at runtime?

Posted by Anatoly Rr on Stack Overflow See other posts from Stack Overflow or by Anatoly Rr
Published on 2010-04-02T13:17:26Z Indexed on 2010/04/02 13:23 UTC
Read the original article Hit count: 366

Filed under:
|
|

I have a model:

class Person (models.Model):
    name     = models.CharField ()
    birthday = models.DateField ()
    age      = models.IntegerField ()

I want to make age field to behave like a property:

    def get_age (self):
        return (datetime.datetime.now() - self.birthday).days // 365

    age = property (get_age)

but at the same time I need age to be a true field, so I can find it in Person._meta.fields, and assign attributes to it: age.help_text = "Age of the person", etc.

Obviously I cannot just override Person.save() method to calculate and store age in the database, because it inevitably will become wrong later (in fact, it shouldn't be stored in the database at all).

Actually, I don't need to have setters now, but a nice solution must have setting feature.

Is it possible in Django, or probably there is a more pythonic and djangoic approach to my problem?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models