SQLAlchemy, Generating python declarative_base classes using reflection AND/OR Persisting reflected metadata and automap_base

时间:2015-05-12 22:27:05

标签: sqlalchemy

I am using SQlAlchemy automap extension for my preference to avoid manually writing up the declarative base classes. Mostly because I am not very familiar with the db schema and need to interact only with a small subset of tables and columns

I am using the following code to set up a SQlAlchemy session and then interact with my database. Things seem to work well using this.

self

Since the database has a large number of tables and columns, it takes a fair amount of time for the session to load, since each time reflection has to be done.

Also, the IDE I use (PyCharm) gives me very useful auto completion when it can infer the object type correctly. It does not work when I use automap, for obvious reasons. It is often a challenge to get the column name strings right, and requires me to repeatedly verify them from db management studio.

Is there a way to generate declarative base classes using reflection? Can I at least persist the reflected metadata in some other way? It is safe to assume that db schema won't change.

1 个答案:

答案 0 :(得分:1)

You can define models that represent the tables in the database. Given that the database is not expected to change much this only needs to be done once, possibly with some column changes later on.

Example:

closest("img")

Documentation