Colleen
Colleen

Reputation: 25479

how to get the table name from a sqlalchemy query

I've read through the query docs and don't see anywhere if there is a way to get the tablename from a query-- e.g. if I have q = query(Users), can I get Users back out from q?

Upvotes: 8

Views: 2249

Answers (2)

Qi Ivan
Qi Ivan

Reputation: 1

@vvladymyrov 's answer only worked for sqlalchemy v1.4

for v2.x use

from sqlalchemy import Table
from sqlalchemy.sql import Join
froms = query.selectable.get_final_froms()
if isinstance(froms[0], Join):
    froms = froms[0]._from_objects
for t in froms:
    print(t.name)

Upvotes: 0

vvladymyrov
vvladymyrov

Reputation: 5793

Please note that event simple query like yours may involve other table then Users too in case when they are related. So you'll need to iterate over it.

The following should do what you need .selectable.locate_all_froms():

for t in query.selectable.locate_all_froms():
    print repr(t)
    print "table name: %s " % t.name

Will result in something like that:

>>>Table('order', MetaData(bind=None), Column('id', Integer(), table=<order>, primary_key=True, nullable=False, default=Sequence('order_seq', metadata=MetaData(bind=None))), Column('name', String(length=127), table=<order>), schema=None)
>>>table name: order

This should work for query build from Mapped object and also for query build from Table object.

Upvotes: 7

Related Questions