2

I know how to get the columns that would be returned from a select statement but how do I get the entities that would be returned from an sqlalchemy.orm.Query object?

>>> sess = Session()
>>> q = sess.query(Entity1, Entity2)
>>> q.statement.c.keys()
['e1_col1', 'e1_col2', ..., 'e2_col1', 'e2_col2, ...]

I want [Entity1, Entity2] or something similar!

3 Answers 3

3

Update: A better approach now exists, see @exhuma answer. My old answer from 2010 follows.

You can try this:

[e.mapper.class_ for e in q._entities]

Although I would prefer not to use _entities attribute directly and find some other way to access it, but AFAIK there is none.

Sign up to request clarification or add additional context in comments.

1 Comment

_entities no longer exists on the query object. This answer is obsolete. See stackoverflow.com/a/72978285/160665
1

This is indirectly available via Query.column_descriptions:

entities = {item['entity'] for item in query.column_descriptions}

This uses a set instead of a list to avoid duplicates in case of a query that selects specific columns (f.ex.: query = session.query(Foo.bar, Foo.baz)). The column_descriptions attribute contains an entry for each selected column so this would cause duplicates.

Comments

-1

sqlalchemy_utils module has a function called get_query_entities that does the job

https://sqlalchemy-utils.readthedocs.io/en/latest/orm_helpers.html#sqlalchemy_utils.functions.get_query_entities

1 Comment

get_query_entities does not seem to exist on that library. And there is a "native" way to solve this. See stackoverflow.com/a/72978285/160665

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.