r/FastAPI • • Aug 04 '20

serialization of sqlalchemy quer result

i have this query

def get_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()

and this model

class User(Base):
__tablename__ = "myusers"

id = Column(Integer, primary_key=True, unique=True, nullable=False) name = Column(String) password = Column(String) usertype = Column(Integer)

this is my endpoint

@app.get("/users/")
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud.get_users(db, skip=skip, limit=limit)
    return BaseResponse(code=status.HTTP_200_OK, status=True, result=users)

and this is the base_response class

class BaseResponse(BaseModel):
status: bool = Field(True)
code: int
result: Optional[dict] = None
error: Optional[Error] = None

I am getting this error

validation error for BaseResponse result value is not a valid dict (type=type_error.dict)

I tried using marshmallow-sqlalchemy but still getting the same error

0 Upvotes

1 comment sorted by

View all comments

1

u/zeetee Aug 05 '20

The result value in BaseResponse is a list of User objects, not a dict. In the FastAPI doc for SQLAlchemy it shows you how to add Config to your Pydantic model with an orm_mode setting.