Generate SQLAlchemy models from Pydantic models

Question:

So I have this large JSON dataset with a huge number of properties (as well as nested objects). I have used datamodel-code-generator to build pydantic models. The JSON data has been imported into pydantic models (with nested models).

Now I need to push them into the database.

How can I automatically generate SQLAlchemy/SQLModel (or any other ORM) model definition classes from pydantic models?

Note: SQLModel and Pydantic seem to have similar syntax for model definition, so I guess I could copy-paste the pydantic models and edit as necessary. But I’m not that familiar with SQLModel yet. I was wondering if there was an automated way to do this.

Asked By: masroore

||

Answers:

There are several python packages that add an ORM layer on top of Pydantic.

Pynocular – supports pgsql only

pydbantic – lightweight ORM on top of pydantic models.

SQLModel – from the author of FastAPI. I’d chosen to go with sqlmodel as it provides the power of SQLAlchemy under the hood.

Answered By: masroore