🐛 Fix issues introduced by removing SQLAlchemy safeguard in jsonable_encoder #1987
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
🐛 Fix issues introduced by removing SQLAlchemy safeguard in
jsonable_encoder
.The
jsonable_encoder
originally had asqlalchemy_safe=True
parameter that would avoid trying to encode any object attribute starting with_sa
, as SQLAlchemy creates several attributes with that prefix in the models.It was there as a quick and early workaround/hack to allow working with SQLAlchemy easily. But I didn't really want to have ORM-specific logic in FastAPI, as FastAPI is independent of ORM (or DB, you could just use MongoDB or ElasticSearch as well).
The main workflow for using any type of ORM with FastAPI is with Pydantic's ORM mode, as described in Tutorial: SQL (Relational) Databases that feature has been there for a long while. So I expected the
jsonable_encoder
to no longer need that workaround. But I had used the same workaround in e.g. the project generator: https://github.com/tiangolo/full-stack-fastapi-postgresql/blob/master/%7B%7Bcookiecutter.project_slug%7D%7D/backend/app/app/crud/base.py#L35 🤦So, for now, I'm reverting it, for the cases that depended on it, as noticed by @shawnwall on #1864 (comment)
Later I would like to remove the SQLAlchemy-specific logic.
But I think it would have to be something like discarding arbitrary object attributes that start with
_
(but this would include, e.g. a MongoDB ORM object with an_id
attribute). Although this would only apply to objects, not dictionaries. And only in the case where it's an arbitrary object, not a Pydantic model.