How to make a Django model fields calculated at runtime?
- by Anatoly Rr
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?