'Get the MAX Datetime Less Than a Value in SQLAlchemy

I want to get the MAX of a datetime column that is less than a particular value. It is the equivalent of this query in SQL,

SELECT MAX(effective_date)
FROM organization_his
WHERE effective_date < '2022-02-10 06:20:10';

This SQL query works perfectly fine.

This is how I have written it in SQLAlchemy,

self.session.query(func.max(getattr(self.__get_table('organization_his'), 'effective_date'))).filter(
  getattr(self.__get_table('organization_his'), 'effective_date') < self.datetime
).one()

self.datetime is a datetime in string format. For example, '2022-02-10 06:20:10'.

This is what I see when I print the query,

SELECT max(private_data_ingestion.organization_his.effective_date) AS max_1 
FROM private_data_ingestion.organization_his 
WHERE private_data_ingestion.organization_his.effective_date < %(effective_date_1)s

I have just used a few generic ways to get the table and column values from the model. This is my __get_table() function, just FYI,

def __get_table(self, table_name):
    for c in self.base._decl_class_registry.values():
        if hasattr(c, '__tablename__') and c.__tablename__ == table_name:
            return c

I keep getting None when I run the SQLAlchemy code. What am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source