-
-
Notifications
You must be signed in to change notification settings - Fork 6.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support SQLAlchemy models with hybrid properties #218
Comments
@omrihar I'm working on improving the way we handle this in a PR to Pydantic here: pydantic/pydantic#520 This would help to solve this, even for nested relationship/models, lists of results, etc. |
FastAPI now has a deep integration with the new Pydantic ORM mode. This includes support for hybrid properties, lazy-loading, and many other things. Check the new docs here: https://fastapi.tiangolo.com/tutorial/sql-databases/ |
Hi @tiangolo , great work! I read through the very thorough docs and I really like it :) And orm_mode as well :) I guess this issue can be closed now... I'm thinking of refactoring my app (based on the fullstack cookiecutter) to reflect the changes. |
Great! Thanks for reporting back and closing the issue. Just so you know, the cookiecutter is not updated yet with these new changes. |
Is your feature request related to a problem? Please describe.
I would like to be able to return an SQLAlchemy model and have it cast to a Pydantic schema. The problem is that hybrid properties on SQLAlchemy do not appear in the
__dict__
variable of the model and therefore do not appear in thevars()
function.Describe the solution you'd like
I would like
json_encodable
to support SQLAlchemy models with hybrid properties. It is possible to use the inspection function of SQLAlchemy to achieve this:however I'm not sure how to extract the field name from this procedure.
Describe alternatives you've considered
A different alternative, which @tiangolo mentioned, is to try to obtain the property by name bsed on the pydantic model. This will also work, if we use
getattr
. For example, if I have anItem
instance calleditem
with a hybrid propertytitle
, it's possible to get it byitem.title
orgetattr(item, 'title')
, but not by usingitem['title']
oritem.get('title')
.Additional context
I'm using
sqlalchemy_utils
to provide translations-aware models. This only works on PostgreSQL. The field in the table is called, for exampletitle_tr
which is aJSONB
field that has keys as language names and as values the translations. Then thesqlalchemy_utils.TranslationHybrid
is a property on the instance that takes the value of thetitle_tr['current_locale']
.See https://sqlalchemy-utils.readthedocs.io/en/latest/internationalization.html.
The text was updated successfully, but these errors were encountered: