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?
To access the column names we can use the method keys() on the result. It returns a list of column names. Since, we queried only three columns, we can view the same columns on the output as well.
Metadata contains definitions of tables and associated objects such as index, view, triggers, etc. Hence an object of MetaData class from SQLAlchemy Metadata is a collection of Table objects and their associated schema constructs.
create_all() function to create the tables that are associated with your models. In this case you only have one model, which means that the function call will only create one table in your database: from app import db, Student. db.
SQLAlchemy now refers to these two mapping styles as imperative mapping and declarative mapping. Regardless of what style of mapping used, all ORM mappings as of SQLAlchemy 1.4 originate from a single object known as registry , which is a registry of mapped classes.
Information you need you can get from Table object:
Ship.__table__.columns
will provide you with columns informationShip.__table__.foreign_keys
will list foreign keysShip.__table__.constraints
, Ship.__table__.indexes
are other properties you might find usefulIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With