FastAPI创建帖子返回Pydantic ValidationError: date_create字段缺失怎么解决
报错原因
这是字段名拼写不匹配导致的Pydantic校验失败:
- 数据库
posts表的创建时间字段命名为date_created - SQLAlchemy的
Post模型中对应的字段命名也为date_created - 但返回用的Pydantic
PostSchema中,创建时间字段被错误写为date_create(缺少末尾的d)
开启orm_mode后Pydantic会直接从返回的ORM对象中按字段名匹配取值,ORM对象不存在date_create属性,因此抛出field required的校验错误。
修复方案
修改Pydantic定义的Post Schema,将错误的字段名修正为和模型、数据库一致即可:
class Post(PostBase): id: int owner_id: int # 把原来的date_create改为date_created date_created: dt.datetime date_last_updated: dt.datetime class Config: orm_mode = True
修改完成后重启服务,再次调用接口即可正常返回数据。
内容的提问来源于stack exchange,提问作者JoeZHH
相关产品推荐
相关产品推荐

