Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to discover table properties from SQLAlchemy mapped object

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?

like image 691
Olivier Girardot Avatar asked Mar 14 '10 10:03

Olivier Girardot


People also ask

How do I get column names in SQLAlchemy?

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.

What is MetaData in SQLAlchemy?

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.

What does DB Create_all () do?

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.

What is mapping in SQLAlchemy?

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.


1 Answers

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
like image 196
van Avatar answered Oct 14 '22 08:10

van