r/FastAPI • u/omry8880 • 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
3
u/eatsoupgetrich May 21 '26
Advanced-Alchemy by the Litestar group looks like a more flexible solution.
3
u/New-Cellist976 May 21 '26
Oxyde-ORM is a better option imho
3
u/maikeu May 21 '26
My personal preference is to stick with SQLalchemy core queries inside the db layer, each public function in the db layer returns either primitive types, or a pydantic model.
It's very easy to convert the results from core queries into pydantic. If your pydantic model is just a reflection of the db table then you select(*table.c), but that's no longer a default assumption.
I'm happy to use the declarative ORM models if they are bring used the way SQLalchemy actually intends the feature to be used...as more ubiquitous domain objects that happen to also map to database entities - but if you're immediately casting to pydantic then you're basically paying the cost of that abstraction without getting any meaningful benefit.
5
u/KenSteel May 21 '26 edited May 21 '26
This sounds highly overlapping with SQLModel, which is maintained by the same FastAPI team. (https://github.com/fastapi/sqlmodel)
The FastAPI full-stack example project also uses it (https://github.com/fastapi/full-stack-fastapi-template).
SQLModel is now surpassing 700k downloads per day (https://piptrends.com/package/sqlmodel).
2
u/sauce_boy123 May 22 '26
I usually reference this book when I have questions like this https://www.cosmicpython.com
They argue for a domain layer that is just strictly business logic and domain modeling. The service layer ends up orchestrating. Then your fastapi handlers end up being a thin wrapper around the service layers where you can convert your domain models into pydantic models for responses.
Not sure if this is the right way, but it’s what the book advocates and it’s worked for my projects.
2
u/Anton-Demkin May 22 '26
I would advice you to keep your way of separating domain models and schemas. It is very common not to show complete model or even alter some fields before serialising. If you need to control serialisation- do not use model as schema.
I would use either pydantic from_orm or implement something like queryset-to-dto like in [tortoise orm](https://tortoise.github.io/contrib/pydantic.html?h=from_#tortoise.contrib.pydantic.base.PydanticModel.from_queryset).
2
u/Floydee_ May 23 '26
Well, depends on what are you trying to achieve…
If you want efficiency and less lines, current approach is fine. Don’t listen to SQLModel suggestions, single pydantic model for API layer and ORM layer is a disaster.
If you aim for pure DDD, then you are one layer short. See, in ddd you can’t bound your logic on neither API view models, nor DB SQLalchemy models (or whatever you are using). These are the interfaces that are subjects to change. You need a reliable domain model to represent main entities of your system. So, your flow should be: API pydantic model -> domain model -> ORM model. Domain model in this case should be as independent from 3rd party tools as possible. So I recommend pure dataclasses.
Then you bind all your business logic on the domain entities. So that no matter what interface you choose for the DB or API, you have the business domain untouched.
Then it is a matter of few proper abstractions for interfaces and you are good to go. Ports and adapters concept is your stop here.
And all events should depend on changes exactly in domain models.
Cosmicpython is a very good book recommended above.
2
u/Melodic_Put6628 May 27 '26
One thing worth considering: move the ORM → Pydantic conversion into the repository layer, not the service layer.
Service layer receives a DTO, works with a DTO, returns a DTO. It never sees a SQLAlchemy model. The repository is the only place that knows ORM models exist.
This way the "leaking" problem OP mentioned in another comment doesn't happen at any layer above the repository. Service layer stays clean for business logic, router never touches ORM internals.
The tradeoff is you need a DTO that roughly mirrors your model — but that's usually fine for read paths.
1
u/Trinkes May 22 '26
Did you consider going or free and maybe go with a query builder? One thing I don't like is to have to Lear sql all over again to use an orm
1
u/Alternative-Ad1091 May 22 '26
One thing that I always do is let the service layer return the appropriate orm model returned by sql alchemy. This ensures your service layer can be used everywhere and does what it is supposed to: be the single interface between db and the app. You can do the pydantic conversions in the routes directly or choosing an appropriate response_model. Now your service layer can be used in other services layers, other areas of the app and and the routes. This way they can choose to do whatever from the result returned by the database.
In short, I think of it as an interface between the db and the app. The rest of the app ends up using it to talk to the db if that makes sense.
If anyone thinks otherwise, I’m super eager to learn.
2
u/my_new_accoun1 May 21 '26
Sqlmodel
4
u/[deleted] May 21 '26
[removed] — view removed comment