开发者

Find Table object in query

开发者 https://www.devze.com 2023-04-02 08:08 出处:网络
Using sqlalchemy 0.7.2 Is there a way to find the table class from the query object?For example: q = session.query(Customers)

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消