33

I have a class mapped with a table, in my case in a declarative way, and I want to "discover" table properties, columns, names, relations, from this class:

engine = create_engine('sqlite:///' + databasePath, echo=True)

# setting up root class for declarative declaration
Base = declarative_base(bind=engine)

class Ship(Base):
    __tablename__ = 'ships'

    id = Column(Integer, primary_key=True)
    name = Column(String(255))

    def __init__(self, name):
            self.name = name

    def __repr__(self):
            return "<Ship('%s')>" % (self.name)

So now my goal is from the "Ship" class to get the table columns and their properties from another piece of code. I guess I can deal with it using instrumentation but is there any way provided by the SQLAlchemy API?

Ken Redler
  • 23,863
  • 8
  • 57
  • 69
Olivier Girardot
  • 4,618
  • 6
  • 28
  • 29

2 Answers2

63

Information you need you can get from Table object:

  • Ship.__table__.columns will provide you with columns information
  • Ship.__table__.foreign_keys will list foreign keys
  • Ship.__table__.constraints, Ship.__table__.indexes are other properties you might find useful
0x78f1935
  • 465
  • 6
  • 10
van
  • 74,297
  • 13
  • 168
  • 171
  • 2
    Is there a way to get attributes declared using `@declared_attr` in base classes in the body of the class itself? I would like to declare column using sequence with the name of sequence created based on table's name which is itself defined in a base class using `@declared_attr`. – Piotr Dobrogost Apr 13 '16 at 13:06
0

If declarative base is not used, the answer fails. The following should work no matter how it's initialized

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