Search code examples
pythonpropertiesflask-sqlalchemyhybrid

TypeError: sqlalchemy properties -> class 'sqlalchemy.orm.attributes.InstrumentedAttribute'


I have the following sqlalchemy class (simplified):

class Persons(Base):
    __tablename__ = 'm_persons'
    birthDate = db.Column(db.Date, nullable=True)
    @hybrid_property
    def age(self):
        bd = self.birthDate
        return relativedelta(date.today(), bd).years
    @age.expression
    def age(cls):
        bd = cls.birthDate
        return relativedelta(date.today(), bd).years

when I use the property to print the value as

person = Person.query.get(1)
print(person.age)

It correctly prints the age of the person. Now when I try to use the property into a query like:

Persons.query.filter(Persons.age >= min_age).all()

Then I got the following error :

TypeError: relativedelta only diffs datetime/date

Which I understand as cls.birthDate is of type

class 'sqlalchemy.orm.attributes.InstrumentedAttribute'

So the question what I am missing to get the value of the property birthDate?

Of course I have been 'googleing' around and read the doc but could not find the reason why it is not working or a solution.

Any help would be appreciated.

*** EDIT **** The trace of the error :

File "/Users/ext334/Dev/python/asocio/app/members/forms.py", line 174, in __init__
    self.person.choices = listPersons(gender=subscription.gender, min_age=subscription.min_age, max_age=subscription.max_age)
  File "/Users/ext334/Dev/python/asocio/app/members/forms.py", line 31, in listPersons
    print(Persons.query.join(Members).filter(Persons.age >= min_age, Persons.age <= max_age, extract('year',Persons.birthDate) >= minBirthYear, extract('year',Persons.birthDate) <= maxBirthYear, Persons.sex == gender).order_by(Members.lastname, Members.firstname))
  File "/Users/ext334/Dev/python/venv36/lib/python3.6/site-packages/sqlalchemy/ext/hybrid.py", line 867, in __get__
    return self._expr_comparator(owner)
  File "/Users/ext334/Dev/python/venv36/lib/python3.6/site-packages/sqlalchemy/ext/hybrid.py", line 1066, in expr_comparator
    owner, self.__name__, self, comparator(owner),
  File "/Users/ext334/Dev/python/venv36/lib/python3.6/site-packages/sqlalchemy/ext/hybrid.py", line 1055, in _expr
    return ExprComparator(cls, expr(cls), self)
  File "/Users/ext334/Dev/python/asocio/app/members/models.py", line 235, in age
    return relativedelta(date.today(), cls.birthDate).years
  File "/Users/ext334/Dev/python/venv36/lib/python3.6/site-packages/dateutil/relativedelta.py", line 102, in __init__
    raise TypeError("relativedelta only diffs datetime/date")
TypeError: relativedelta only diffs datetime/date

The full query :

Persons.query.join(Members).filter(Persons.age >= min_age, Persons.age <= max_age, extract('year',Persons.birthDate) >= minBirthYear, extract('year',Persons.birthDate) <= maxBirthYear, Persons.sex == gender).order_by(Members.lastname, Members.firstname)

The full class Persons :

class Persons(Base):
    """
    Description of a person
    """
    __tablename__ = 'm_persons'
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE', onupdate='CASCADE'))
    family_id = db.Column(db.Integer, db.ForeignKey('m_families.id', ondelete='CASCADE', onupdate='CASCADE'))

    birthDate = db.Column(db.Date, nullable=True)
    sex = db.Column(db.String(1), nullable=False, default='U') # U = unknown, F = Female, M = Male


    # return the age in years, not rounded

    @hybrid_property
    def age(self):
        return relativedelta(date.today(), self.birthDate).years

    @age.expression
    def age(cls):
        return relativedelta(date.today(), cls.birthDate).years

Solution

  • Well I found a workaround or maybe I better understood how it worked. In @age.expression you can execute the functions of your database. So I decided to calculate the age inside this @age.expression based on the MySQL

    Here the code :

    @age.expression
    def age(cls):
        return func.year(func.from_days(func.to_days(date.today()) - func.to_days(cls.birthDate)))
    

    Basically, this calculate the number of years between the birthdate and now. So the flask-sqlalchemy query is

    Persons.query.join(Members).filter(Persons.age >= min_age, Persons.age <= max_age, extract('year',Persons.birthDate) >= minBirthYear, extract('year',Persons.birthDate) <= maxBirthYear, Persons.sex == gender).order_by(Members.lastname, Members.firstname)
    

    The generated sql statement is:

    SELECT m_persons.id AS m_persons_id, m_persons.date_created AS m_persons_date_created, m_persons.date_modified AS m_persons_date_modified, m_persons.user_id AS m_persons_user_id, m_persons.family_id AS m_persons_family_id, m_persons.`birthDate` AS `m_persons_birthDate`, m_persons.sex AS m_persons_sex FROM m_persons INNER JOIN users ON users.id = m_persons.user_id WHERE year(from_days(to_days(%s) - to_days(m_persons.`birthDate`))) >= %s AND year(from_days(to_days(%s) - to_days(m_persons.`birthDate`))) <= %s AND EXTRACT(year FROM m_persons.`birthDate`) >= %s AND EXTRACT(year FROM m_persons.`birthDate`) <= %s AND m_persons.sex = %s ORDER BY users.lastname, users.firstname
    

    and thus the @age.expression returns year(from_days(to_days(%s) - to_days(m_persons.birthDate))) which is well understood in the query

    As a summary I would say that in the @age.expression you can only applied database function and not really operate on the column itself.