Python 当我使用fastapi和pydantic构建POST API时,会出现一个TypeError:类型的对象不可JSON序列化

Python 当我使用fastapi和pydantic构建POST API时,会出现一个TypeError:类型的对象不可JSON序列化,python,fastapi,pydantic,Python,Fastapi,Pydantic,我使用FastAPi和Pydantic对POST API的请求和响应进行建模 我定义了三个类: from pydantic import BaseModel, Field from typing import List, Optional, Dict class RolesSchema(BaseModel): roles_id: List[str] class HRSchema(BaseModel): pk: int user_id: str worker_i

我使用FastAPi和Pydantic对POST API的请求和响应进行建模

我定义了三个类:

from pydantic import BaseModel, Field
from typing import List, Optional, Dict

class RolesSchema(BaseModel):
    roles_id: List[str]

class HRSchema(BaseModel):
    pk: int
    user_id: str
    worker_id: str
    worker_name: str
    worker_email: str
    schedulable: bool
    roles: RolesSchema
    state: dict

class CreateHR(BaseModel):
    user_id: str
    worker_id: str
    worker_name: str
    worker_email: str
    schedulable: bool
    roles: RolesSchema
以及我的API程序:

@router.post("/humanResource", response_model=HRSchema)
async def create_humanResource(create: CreateHR):
query = HumanResourceModel.insert().values(
    user_id=create.user_id, 
    worker_id=create.worker_id, 
    worker_name=create.worker_name,
    worker_email=create.worker_email,
    schedulable=create.schedulable,
    roles=create.roles
)
last_record_id = await database.execute(query)
return {"status": "Successfully Created!"}
输入数据格式为json:

{
     "user_id": "123",
     "worker_id": "010",
     "worker_name": "Amos",
     "worker_email": "Amos@mail.com",
     "schedulable": true,
     "roles": {"roles_id": ["001"]}
}
执行时,我得到了TypeError:RoleSchema类型的对象不可JSON序列化


如何将程序修复为正常运行?

尝试使用
roles=create.roles.dict()
创建
query
而不是
roles=create.roles
谢谢您的回复。这是工作!!!