Harper
Harper

Reputation: 1223

SQLAlchemy: Auto generate class definitions for a legacy database

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

Upvotes: 13

Views: 9124

Answers (1)

Harper
Harper

Reputation: 1223

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.

Upvotes: 21

Related Questions