In python SQLAlchemy we can create a raw string query from an SQLAlchemy query object using the following code:
str(query.compile(compile_kwargs={"literal_binds": True}))
But I want to do a reverse operation. I have a raw string SQL query (generated from the above code) and want to transform it back to original SQLAlchemy query object from which I actually convert it to string.
I tried the following code:
db.session.query().from_statement(db.text(query_str))
but I can't locate columns in the generated SQLAlchemy query object. I can't mention any column/model in query(...) because query is totally dynamic and not simple like it gets data from inner query and with lot of joins.
So, actual SQLAlchemy query object looks like following where we can see all columns and other query parts:
But below is the SQLAlchemy query object which we get from raw SQL string:
References: