0

Is there a way I can print a query created by sqlalchemy

emp = session.query(Employee).filter(*empfilters).order_by(Employee.Name).all()

I've tried doing str(emp), emp.statement.compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}) or other solutions from SO, but couldn't reproduce anything. The *empfilters again here comes from other tables (part of one-many join) so I wanted to check what exactly it's being compiled to.

The error if I try to do it by above is - 'list' object has no attribute 'statement'

4
  • 2
    The query ends at order_by(Employee.Name). When you use .all() at the end, the query runs and returns a list, hence your error message. If you remove .all() you should be able to examine the query string.
    – ac24
    Commented Mar 19, 2020 at 8:55
  • global name 'postgresql' is not defined -- Do I need to add it @ac24?
    – Aniruddha
    Commented Mar 19, 2020 at 9:48
  • Just str(emp) should let you view the query in native sql. If you are having other issues please include more code to demonstrate empfilters etc.
    – ac24
    Commented Mar 19, 2020 at 10:19
  • Thanks. I was able to print it by removing all() and then doing print emp
    – Aniruddha
    Commented Mar 19, 2020 at 15:18

1 Answer 1

0

Based on the recommendation from @ac24, removed the .all() from the query and then print emp did the trick.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.