How can I auto-generate class definitions for SQLAlchemy, including relationships and backref, as the Django-ORM does with manage.py inspectdb?
-
3@Ilja Everilä The question was not written as a tool request. A totally legitimate answer would be an approach for how to write code to do this. As it happens there's a good tool for the job, and that seems a better answer.Sam Hartman– Sam Hartman2017-09-25 23:42:47 +00:00Commented Sep 25, 2017 at 23:42
-
Harper: to help the unanswered questions queue to stay low consider to check your own answer. Thanks.Paolo– Paolo2017-09-26 01:08:04 +00:00Commented Sep 26, 2017 at 1:08
Add a comment
|
1 Answer
You can use the python package sqlacodegen for exactly this purpose.
sqlacodegen will inspect the database and generate SQLAlchemy style class definitions for future reference and store them in a file.
https://pypi.python.org/pypi/sqlacodegen
Usage:
pip install sqlacodegen- Start from command line:
sqlacodegen [connection string] [options]
The generated class definitions are largely correct and include index definitions and constraints (foreign keys).
In my case, it saved me from typing out 19.000 rows of class definitions.
3 Comments
Fahim
Hi @Harper Thanks for sharing, this is a good one but the only problem it works well with SQLAlchemy 1.4 and below Thanks
anjuta
There are multiple forks of sqlacodegen. I am using sqlacodegen_v2, which is available from pypi.org. It's compatible with sqlalchemy 2.
Floriancitt
sqlacodegen was updated 3 weeks ago to work with SQLAlchemy 2.0, version 3.0.0rc5. It's already available on github, but not yet via pypi / pip.