I am trying to calculating the age of an object instance by using the attribute "year".
class User(db.Model):
__tablename__ = 'user'
__table_args__ = {'schema': 'data'}
id = db.Column(db.Integer, primary_key=True, server_default=db.FetchedValue())
birthday = db.Column(db.Date)
@hybrid_method
def age(self):
return datetime.datetime.now().year - self.birthday.year
While
test = User.query.first()
test.year
is returning 20 (correct), the following query is returning an error
test = User.query.filter(User.age==20).all()
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with User.birthday has an attribute 'year'
How can I get the attribute parsed?
EDIT based on comment: Solution 1:
@hybrid_property
def age(self):
return datetime.datetime.today().year - self.birthday.year
@age.expression
def age(cls):
return datetime.datetime.today().year - func.year(cls.birthday)
Solution 2 based on SQLAlchemy - Querying with DateTime columns to filter by month/day/year:
@hybrid_property
def age(self):
return datetime.datetime.today().year - self.birthday.year
@age.expression
def age(cls):
return datetime.datetime.today().year - extract('year', cls.birthday)