Get table name by table class in Sqlalchemy

I want to pass a class to a function and don't want to pass that 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'm looking for it using google and there is no answer.

+6
source share
4 answers

In accordance with:

How to find table properties from a mapped SQLAlchemy object

I can use this:

print TableClass.__table__.name
+11
source

Regardless of whether you use a 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

Note that a class may have several mapped tables, for example, when using Inheritance .

+2
source

SQLAlchemy tableclass.

print TableClass.__tablename__ # Prints 't1'p >

@Aylwyn Lake Finding

print TableClass.__table__.name
0
print TableClass.__tablename__

works for me

0
source

Source: https://habr.com/ru/post/1523271/


All Articles