Using SQLAlchemy ORM, Pydantic and Alembic: every model change needs to be reflected in THREE separate places, violates DRY?

Viewed 30

So I am learning FastAPI and want to get more experience with relational databases. I am using SQLAlchemy ORM, Pydantic and Alembic. Database is Postgres. One thing that I am running into however, is when I want to add a single column to a table I need to change a model, a schema and alembic in order to reflect this change. Isn't this a huge violation of DRY, error prone and very hard to maintain in the long run?

1 Answers

Check out SQLModel. It attempts to tackle this exact issue. Instead of defining a database model (SQLAlchemy) and a corresponding Pydantic model, you only define one SQLModel that combines both.

It doesn't change the fact that you need to verify that your Alembic migrations work as intended thought.

The project is still in its early stages, but I find it very promising.

In general, I don't see any benefit in defining the schema twice, when you are developing an API. There is however, the obvious downside of making the entire application much more error prone, when you have to repeat yourself for every change in the schema.

With SQLModel you will probably see a substantial reduction in the lines of code, unless you have very special requirements (such as exotic types, multiple layers of validation/conversion, highly complex/nested relationships).

Related