I have a Flask web application with a Postgres database (<10 million rows). I used SQLAlchemy to connect with Postgres, but queries that I have written in native SQLAlchemy are compiled to SQL that is too slow. The .count() method is one of the main offenders here. I am planning to rewrite my queries. Pseudocode examples:
From db.session.query(Table).filter(Table.column==condition).count()
To db.session.execute(sqlalchemy.text("SELECT count(Table.id) from Table WHERE Table.column=condition")
My question is: can I do better than the execute-text construct? Will this still get wrapped in slow SQLAlchemy logic? Or is this as close to running raw SQL as it gets? How much faster can I tune my Flask-Postgres interaction? (I'm not interested in answers that involve additional third-party services.)