You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用FastAPI和Pydantic定义列表转字典的响应模型?

解决方案

首先定义单个翻译项的Pydantic模型:

from pydantic import BaseModel
from typing import Dict, List

class TranslationItem(BaseModel):
    id: int
    title: str

接着修改文章响应模型,将translation字段定义为字符串键(语言码)到翻译项的字典,匹配目标响应结构:

class ArticleResponse(BaseModel):
    title: str
    description: str
    translation: Dict[str, TranslationItem]

如果从数据库拿到的是带翻译列表的原始数据,用字典推导式就能快速转换为目标格式:

# 示例数据库返回数据
db_article = {
    "title": "For example Title",
    "description": "for example Description",
    "translation": [
        {"id": 1, "lang": "ar", "title": "ar title"},
        {"id": 2, "lang": "fr", "title": "fr title"},
        {"id": 3, "lang": "de", "title": "de title"},
    ],
}

# 转换翻译列表为目标字典
formatted_translations = {item["lang"]: {"id": item["id"], "title": item["title"]} for item in db_article["translation"]}

# 实例化响应模型
response_article = ArticleResponse(
    title=db_article["title"],
    description=db_article["description"],
    translation=formatted_translations
)

这种定义方式适配翻译数量不固定的场景,Pydantic会自动验证每个翻译项的结构,最终输出你需要的嵌套字典格式。

内容的提问来源于stack exchange,提问作者Fathey Abdel slam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 23:02:09