Aylwyn Lake
Aylwyn Lake

Reputation: 2027

Get Table Name By Table Class In Sqlalchemy

I want to pass a class to a function, and don't like to pass the name again.

class TableClass(Base):
    __table__ = Table('t1', metadata, autoload=True)
def get_name(TableClass):
    print TableClass.GetTableName()  # print 't1'
get_name(TableClass)

So, I search it with google, and there is no answer.

Upvotes: 19

Views: 25007

Answers (6)

Hamza Zubair
Hamza Zubair

Reputation: 1410

None of the answers worked for me.

This did:

For Class Object:

TableClass.sa_class_manager.mapper.mapped_table.name

For Instance Object:

tableObj.sa_instance_state.mapper.mapped_table.name

Upvotes: 1

Grizly
Grizly

Reputation: 161

I just hit this issue myself, passing the object around and didn't want to pass the string of the tablename as well..

Turns out, it's just a property of the Table object, eg:

table = new Table("somename",meta)

...
print("My table is called: " + table.name)

Upvotes: 1

van
van

Reputation: 76962

Independent on whether you use declarative extension or not, you can use the Runtime Inspection API:

def get_name(TableClass):
    from sqlalchemy import inspect
    mapper = inspect(TableClass)
    print mapper.tables[0].name

Please note that a class can have multiple tables mapped to it, for example when using Inheritance.

Upvotes: 6

Vermeer Grange
Vermeer Grange

Reputation: 176

print TableClass.__tablename__

works for me

Upvotes: 6

Syed Habib M
Syed Habib M

Reputation: 1817

In SQLAlchemy you can fetch table information with tableclass attributes.

In your example

print TableClass.__tablename__ # Prints 't1'

According to @Aylwyn Lake 's Finding

print TableClass.__table__.name

Upvotes: 1

Aylwyn Lake
Aylwyn Lake

Reputation: 2027

According To:

How to discover table properties from SQLAlchemy mapped object

I can use this:

print TableClass.__table__.name

Upvotes: 31

Related Questions