Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Table object in query

Tags:

sqlalchemy

Using sqlalchemy 0.7.2

Is there a way to find the table class from the query object? For example:

q = session.query(Customers)

how can I find Customers in q? Possible? Not Possible?

like image 999
Michael Beale Avatar asked Sep 03 '11 00:09

Michael Beale


1 Answers

Yes. You need column_descriptions.

It's a long road to the table, though. sqlalchemy.orm.Query.column_descriptions returns a list of dicts, describing each query entity as it was given to query. in your example, there's only one entity, so you need the first item from that list. And since you're interested in the type of the query entity, rather than its' structure, you want the "type" key from that list:

q_entity = q.column_descriptions[0]['type']
assert q_entity == Customer

Accessing the table for the mapped class requires snooping around in the mapper subsystem. for that, you should use manager_of_class. The table is accessible from the manager through the mapper.mapped_table attribute:

from sqlalchemy.orm.attribute import manager_of_class
q_table = manager_of_class(q_entity).mapper.mapped_table

Resist the urge to skip strait to the mapper through Customer.__mapper__, or even Customer.__table__; That's specific to sqlalchemy.ext.declarative, and won't work with classes that are mapped by other means.

like image 127
SingleNegationElimination Avatar answered Sep 28 '22 18:09

SingleNegationElimination