pydantic在fastapi中序列化
我会分别问这个问题,但内容不同。
我想序列化连接,然后与pydantic序列化,但它不起作用。
如果可能的话,我想将其返回,就像它是一个对象一样。
{
id: 1,
parent_column: test1,
child_column: test2
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用所需的信息创建一个Pydantic模型,因此该模型将负责序列化为JSON格式。
您只需要通过以请求的格式提供数据来创建模型的响应。
以下是一个带有FastAPI端点的示例,该示例将使用ID检索特定数据并使用特定模板返回JSON响应。
之后,可以通过pydantic类的
orm_mode
将Pydantic模型与SQLalchemy联系起来。更多信息在这里:You can create a Pydantic model with the information you want, so the model will take care of the serialization to JSON format.
You just have to create a response from your model by providing it with the data in the requested format.
Below is an example given with a fastAPI endpoint that would take an ID to retrieve a specific data and return a JSON response with a specific template.
Afterwards, it is possible to link Pydantic models with sqlalchemy via the
orm_mode
of the Pydantic class. More information here: https://fastapi.tiangolo.com/tutorial/sql-databases/#use-pydantics-orm_mode