PAYATHON 2026

FastAPI 返回嵌套对象时,为什么会遗漏已有值的字段?

数据阿明

从现有代码看,应先修正数据库对象到响应模型的转换:将查询得到的每个 IngredientModel 显式转换为 IngredientBody,并分别把 measurement 和 unit 映射到 ingredientMeasurement 和 ingredientUnit。

这是代码中最明显的疑点。由于没有提供 IngredientModel 定义、路由装饰器以及 FastAPI/Pydantic 版本,还不能断言字段被省略的具体序列化路径。

为什么有值的字段仍可能消失?

查询使用的是:

statement = select(IngredientModel).where(
    IngredientModel.componentId == componentId
)

查询结果随后被直接赋给父对象:

componentBody.componentIngredients = ingredients

父对象声明的元素类型是:

componentIngredients: list[IngredientBody] | None = []

类型注解本身不会在每次赋值时自动将数据转换成对应模型。在未启用赋值验证的常见配置下,赋值后列表中仍可能保存的是 IngredientModel 实例。

再看 IngredientBody.toModel():

model.measurement = self.ingredientMeasurement
model.unit = self.ingredientUnit

数据库对象和响应对象的字段名并不完全相同:

数据库对象属性 响应模型字段
ingredientId ingredientId
ingredientName ingredientName
measurement ingredientMeasurement
unit ingredientUnit

前两个名称一致,后两个需要映射。toModel() 把 IngredientBody 转换为 IngredientModel,当前返回流程也没有调用它,因此它不会完成从查询结果到响应对象的映射。

这也是应重点检查缺失的两个字段的原因。运行时表现为字段遗漏、警告还是验证错误,仍取决于实际模型、版本和响应配置。

在 Service 中显式构造响应对象

假设 IngredientModel 的属性确实叫作 measurement 和 unit,可以将 Service 方法改为:

def getComponentDetail(componentId):
    ingredients = componentDataProvider.findIngredientsByComponentId(componentId)
    directions = componentDataProvider.findDirectionsByComponentId(componentId)
    component = componentDataProvider.findComponentById(componentId)

    ingredientBodies = [
        IngredientBody(
            ingredientId=ingredient.ingredientId,
            ingredientName=ingredient.ingredientName,
            ingredientMeasurement=ingredient.measurement,
            ingredientUnit=ingredient.unit,
        )
        for ingredient in ingredients
    ]

    directionBodies = [
        DirectionBody(
            directionId=direction.directionId,
            directionOrder=direction.directionOrder,
            directionText=direction.directionText,
        )
        for direction in directions
    ]

    return ComponentBody(
        componentId=component.componentId,
        componentName=component.componentName,
        componentLink=component.originalLink,
        componentNotes=component.componentNotes,
        componentIngredients=ingredientBodies,
        componentDirections=directionBodies,
    )

这样,componentIngredients 中就是实际的 IngredientBody 实例,四个字段都通过参数明确提供。若值缺失或不满足字段类型要求,模型构造阶段就能暴露问题。

DirectionBody 的字段名与 toModel() 中使用的数据库属性名一致,这与 direction 数据能够正常返回的现象相符。示例也对它进行了显式转换,使两个列表采用相同的组装方式。

明确接口的响应模型

如果接口尚未声明 response_model,可以补上。下面的路径仅作示例,实际使用时保留项目已有路径:

@router.get("/components/{componentId}", response_model=ComponentBody)
def getComponentDetail(componentId: int):
    return componentService.getComponentDetail(componentId)

response_model 用于声明接口对外返回的结构,但不会自动推断 measurement 对应 ingredientMeasurement。仍需通过显式构造或合适的模型配置完成字段转换。

也不要只把已有的赋值语句移到构造函数中,就期待不同名称的属性自动匹配。上面两项映射仍需明确指定。

如何确认问题发生在哪一步?

先检查查询结果的实际类型和属性:

for ingredient in ingredients:
    print(type(ingredient))
    print("measurement:", getattr(ingredient, "measurement", "<missing>"))
    print("unit:", getattr(ingredient, "unit", "<missing>"))
    print(
        "ingredientMeasurement:",
        getattr(ingredient, "ingredientMeasurement", "<missing>"),
    )
    print("ingredientUnit:", getattr(ingredient, "ingredientUnit", "<missing>"))

如果 measurement、unit 有值,而响应模型对应名称的属性不存在,就应完成字段映射。若实际属性名不同,则以 IngredientModel 的真实定义为准调整转换代码。

再检查转换后的对象:

for ingredient in ingredientBodies:
    print(type(ingredient))
    print(ingredient.ingredientMeasurement, ingredient.ingredientUnit)

如果显式转换后模型中的值正确,但 HTTP 响应仍缺字段,再检查完整路由上的 response_model、response_model_include、response_model_exclude,以及自定义序列化逻辑。原始材料没有提供这些配置,不能排除它们的影响。

单独返回数据库列表时数据完整,只能证明该返回路径能够序列化这些数据;嵌入带类型声明的父模型后,可能会经过不同的序列化处理。手动 JSON 编码也无法补回前一步已经丢失的字段。

列表默认值可以顺手调整

如果业务约定这两个字段始终返回列表,可以使用:

from pydantic import Field

componentIngredients: list[IngredientBody] = Field(default_factory=list)
componentDirections: list[DirectionBody] = Field(default_factory=list)

这样可以清楚地表达“没有数据时返回空列表”的约定。如果接口确实允许 null,应保留相应的类型设计。这项调整不能解决字段名称不一致的问题。

另外,当前 ingredientMeasurement、ingredientUnit 是必填字段。如果数据库允许它们为 None,需要根据接口约定处理空值,或调整响应类型,不能通过省略字段掩盖数据不符合模型的问题。

备注:内容仅供参考。