13

How can I auto-generate class definitions for SQLAlchemy, including relationships and backref, as the Django-ORM does with manage.py inspectdb?

2
  • 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. Commented Sep 25, 2017 at 23:42
  • Harper: to help the unanswered questions queue to stay low consider to check your own answer. Thanks. Commented Sep 26, 2017 at 1:08

1 Answer 1

22

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi @Harper Thanks for sharing, this is a good one but the only problem it works well with SQLAlchemy 1.4 and below Thanks
There are multiple forks of sqlacodegen. I am using sqlacodegen_v2, which is available from pypi.org. It's compatible with sqlalchemy 2.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.