This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
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
How to use pydantic and sqlalchemy models with relationship #1645
Comments
Try using fastapi's jsonable_encoder instead of pydantic's dict() method: https://fastapi.tiangolo.com/tutorial/encoder/#using-the-jsonable_encoder
|
I agree that we should be able to construct the relationships from the nested orm schemas within the parent schema, but I've only really been able to get this to work by explicitly defining and inserting the children. If there is a better way to do this, I would be interested. |
I agree as well. It seems counter to the entire spirit of modeling in fastapi. Maybe we're missing something. |
@imjohsep - solution is working ,thanks .
parent_data hold all nested trees correctly ....
it somehow breaking it ... @tsh356 - are u sure ur solution solving this ? fatapi V0.63
error:
models:
Schemas:
fastapi:
|
The solution proposed to use The only way I can handle this at the moment is to split the models and then pass the sqlalchemy At the moment I have a model with about ~50 fields, 10 of them are relationships (both one-to-one and one-to-many, the later would require using sqlalchemy's And I have to say I wonder if this is even possible... I could try to help on this, but I confess at the moment I have no idea how. |
The solution proposed to use jsonable_encoder also doesn't work for me too. https://fastapi.tiangolo.com/tutorial/sql-databases/ The example above has no clue for creating an object with relationship. |
@mxdev88 did you have any luck with this? |
I have a generic base class for CRUD, and creating parent with kids as an array I did next: I create the parent from fields that haven't relations and then add relations fields to the object created and commit it. ...
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
obj_in_dict = jsonable_encoder(obj_in, exclude_defaults=True)
obj_in_parent = self.object_as_dict(obj_in_dict)
obj_in_data = self.object_as_dict(obj_in_dict, relationships=True)
db_obj = self.model(**obj_in_parent) # type: ignore
db.add(db_obj)
db.commit()
for key, value in obj_in_data.items():
if key in obj_in_parent or not hasattr(self.model, key):
continue
children = [
getattr(self.model, key).prop.entity._identity_class(**child, item_id=db_obj.id) for child in value
]
setattr(db_obj, key, children)
db.commit()
db.refresh(db_obj)
return db_obj
def object_as_dict(self, obj, relationships=False):
"""
Converts an SQLAlchemy instance to a dictionary.
:param relationships: If true, also include relationships in the output dict
"""
obj_dict = jsonable_encoder(obj, exclude_defaults=True)
properties = inspect(self.model).mapper.all_orm_descriptors
if not relationships:
return {
key: obj_dict[key]
for key, value in properties.items()
if (
not hasattr(value, "prop")
or not isinstance(value.prop, RelationshipProperty)
)
and key in obj_dict
}
else:
return {key: obj_dict[key] for key, value in properties.items() if key in obj_dict}
... |
Did anyone find a better approach to saving and loading objects? |
This issue was moved to a discussion.
You can continue the conversation there. Go to discussion →
Hello,
I'm trying to pass pydantic models to sqlalchemy models based on sql-databases doc.
It works well for single models but fails to work with relationship. I'm expecting to receive an objet nesting several other objects in my endpoint.
Is there a way to do that using the
BaseModel.dict()
like in the documentation or do I need to map my pydantic model to my sqlalchemy model in order to achieve this?Example
Description
data1 works well as expected.
data2 raise AttributeError: 'dict' object has no attribute '_sa_instance_state'
Environment
The text was updated successfully, but these errors were encountered: