full-stack-fastapi-template icon indicating copy to clipboard operation
full-stack-fastapi-template copied to clipboard

CRUD update pattern is broken with fastapi 0.61

Open shawnwall opened this issue 5 years ago • 2 comments

The first line of the CRUDBase update method is:

obj_data = jsonable_encoder(db_obj)

This now stack overflows when using fastapi 0.61. We need an updated base CRUD pattern in this project, along with updating the various dependencies. I'll additionally be filing an issue to the fastapi project itself with the need for CRUD update examples.

From what I've figured out so far, we may need a reference to the ModelInDB or Model pydantic models, and then:

obj_data = ModelInDB.from_orm(db_obj)

and change the iteration to:

for field in obj_data.dict():

shawnwall avatar Aug 18 '20 13:08 shawnwall

I fixed this issue by adding as_dict() to base_class.py in db:

@as_declarative()
class Base:
    id: Any
    __name__: str

    # Generate __tablename__ automatically
    @declared_attr
    def __tablename__(cls) -> str:
        return cls.__name__.lower()

    def as_dict(self) -> dict:
        return {c.key: getattr(self, c.key) for c in inspect(self).mapper.column_attrs}

Then adding as_dict() to the db_obj in update in base.py in crud: obj_data = jsonable_encoder(db_obj.as_dict())

NGRichter avatar Aug 19 '20 19:08 NGRichter

Excuse me. Any examples? I found there is a bug about user update API. e.g.: in crud_user.py

    def update(
        self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
    ) -> User:
        if isinstance(obj_in, dict):
            update_data = obj_in
        else:
            update_data = obj_in.dict(exclude_unset=True)
        # if update_data["password"]:  # may cause a KeyError
        if update_data.get("password", None):  # changed
            hashed_password = get_password_hash(update_data["password"])
            del update_data["password"]
            update_data["hashed_password"] = hashed_password
        return super().update(db, db_obj=db_obj, obj_in=update_data)

kisscelia avatar Sep 03 '20 15:09 kisscelia

Outdated

YuriiMotov avatar Sep 02 '25 18:09 YuriiMotov