r/FastAPI • • May 21 '26

Question ORMs to Pydantic models conversion

I'm developing a side project and trying to follow DDD principles as closely as possible. My current structure is router -> service -> repository. I'm using SQLAlchemy for ORM models, which are created and handled in the repository layer.

Right now, I convert those ORM objects into Pydantic models inside the service layer, and then pass those models to the router, which returns them in the response. I'm wondering whether this is the right approach or if there’s a better pattern for handling the conversion and data flow between layers.

23 Upvotes

42 comments sorted by

View all comments

Show parent comment

1

u/omry8880 May 24 '26

You're right, I'm indeed one layer short.

As the project I'm working on currently isn't that complex or big, I'm fine with that. I mainly wanted to experiment with "application level" DDD and the 3-layer separation.

I'll take your advice and won't change my implementation for now.

Regarding the domain model, is it often just a dataclass identical to the pydantic model?

Will definitely read the book.

Thanks!

2

u/Floydee_ May 25 '26

Regarding the domain model, is it often just a dataclass identical to the pydantic model?

Mostly - yes.
Your pydantic models hold those validations, maybe different API naming conventions, supportive body params etc, basically other kind of non-domain information (and believe me, Pydantic is a full package xd).
Domain models, in opposite, may contain stuff related to internal lifecycle of the entity. For example: you have a process that you run within your system, and that entity can have `_events: list[Event]` collection, or method like: `.finish()` that does certail changes to the entity. API model doesn't need to know these domain details as well as ORM model shouldn't care (ORM abstraction on update should just get updated entity and safely update it).
API model certainly share some common fields, for the user for example it is the name, email, but internally you probably also keep: `id: UserID`, `created_date: datetime`, last_operation: `datetime`.

1

u/omry8880 May 25 '26

Thank you so much for the detailed answers. This helped a lot!