18

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.

Aylwyn Lake
  • 1,919
  • 4
  • 26
  • 36

6 Answers6

29

According To:

How to discover table properties from SQLAlchemy mapped object

I can use this:

print TableClass.__table__.name
Community
  • 1
  • 1
Aylwyn Lake
  • 1,919
  • 4
  • 26
  • 36
6

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.

Nick K9
  • 3,885
  • 1
  • 29
  • 62
van
  • 74,297
  • 13
  • 168
  • 171
5
print TableClass.__tablename__

works for me

Vermeer Grange
  • 146
  • 2
  • 3
1

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
Syed Habib M
  • 1,757
  • 1
  • 17
  • 30
  • `type object 'TableClass' has no attribute '__tablename__'` – Aylwyn Lake Jan 23 '14 at 10:31
  • Yeah You are right. But it will work when you create Table Class using Base Class. As mentioned [here](http://docs.sqlalchemy.org/en/rel_0_9/orm/tutorial.html#declare-a-mapping) – Syed Habib M Jan 23 '14 at 11:28
  • 1
    This assumes that the user is mapping using the `__tablename__` attribute when setting up their code, which while is sometimes the case, is not how the code in the question is set up. – Mark Hildreth Jan 23 '14 at 15:01
  • @MarkHildreth: Than't right. So there are two methods of creating Table Class: one is `__table__`; the other is `__tablename__` – Aylwyn Lake Jan 24 '14 at 02:21
1

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)
Grizly
  • 161
  • 8
1

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
Hamza Zubair
  • 1,232
  • 13
  • 21