I have seen many examples of calculating age in a django model (such as this question). However, most do not have a connection to a database and are simply empty models to be used in pushing to a database. To simplify my example, I have a django model of records of people connected to a SQL Server. I want to, when I query from the DB, also calculate the current age of the person. If I call age
in my view, I get the following error: Cannot resolve keyword 'age' into field
How can I do this, even though age is not a current database field?
class Person(model.Model)
personid = models.IntegerField(db_column='PersonId', primary_key=True)
birth_date = models.DateField(db_column='DOB')
@property
def get_age(self):
return relativedelta(self.birth_date.days, datetime.date.now()).years
def save(self, *args, **kwargs):
self.age = self.get_age()
super(Person, self).save(*args, **kwargs)