0

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)
hans2k6
  • 29
  • 5
  • 1
    Possible duplicate of [SQLAlchemy - using hybrid properties in a query](https://stackoverflow.com/questions/42485423/sqlalchemy-using-hybrid-properties-in-a-query) – J.J. Hakala Feb 21 '19 at 02:34
  • Thank you for your hint! Found also this solution: https://stackoverflow.com/questions/51451768/sqlalchemy-querying-with-datetime-columns-to-filter-by-month-day-year – hans2k6 Feb 22 '19 at 20:28

0 Answers0