【问题标题】:How do I use FastAPI's "response_model_exclude_none=True" to exclude "None" values from nested models?如何使用 FastAPI 的“response_model_exclude_none=True”从嵌套模型中排除“无”值?
【发布时间】:2021-01-22 16:05:54
【问题描述】:

FastAPI 显示您可以在装饰器中设置 response_model_exclude_none=True 以省略值为 None 的字段:https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter

我想这样做,但我想排除的 None 字段嵌套在父响应模型中。即

class InnerResponse(BaseModel):
    id: int
    name: Optional[str] = None

class Response(BaseModel):
    experience: int
    prices: List[InnerResponse]


@app.post("/dummy", response_model=apitypes.Response, response_model_exclude_none=True)
async def backend_dummy(payload: apitypes.Request):
...

但是,当我收到回复时,这里的“价格”列表中仍然有 InnerResponses 和 "name": null

有没有办法对嵌套模型应用排除规则?

【问题讨论】:

  • FastAPI(或 Pydantic)将在 @987654332 @True
  • 顺便说一句,我尝试使用this example from the official doc 重现该行为,但是,我得到了预期的响应,即没有任何None(或null)值的响应
  • 我建议仔细检查您的代码,但问题仍然存在,请添加 最小可验证示例 @maccam912
  • 感谢@ArakkalAbu 对其进行测试。我用代码做了一个新项目,你是对的,它按预期工作。我的问题是这个块之外的代码添加了该字段 BACK IN。另一个 FastAPI 调用我没有设置 response_model_exclude_none=True 的端点。

标签: fastapi pydantic


【解决方案1】:

一种可能性是创建一个继承自BaseModel 的类并覆盖dict 方法:

from pydantic import BaseModel

class AppModel(BaseModel):

  def dict(self, *args, **kwargs):
    if kwargs and kwargs.get("exclude_none") is not None:
      kwargs["exclude_none"] = True
      return BaseModel.dict(self, *args, **kwargs)

现在,从AppModel 创建类:

class InnerResponse(AppModel):
  id: int
  name: Optional[str] = None

class Response(AppModel):
  experience: int
  prices: List[InnerResponse]

【讨论】:

  • 这行不通,因为 FastAPI 将为exclude_none 注入一个False 的值。因此,您还必须在所有路线中手动调用 response.dict()
【解决方案2】:

对于在搜索时发现此问题的任何人:上面的代码运行良好,但我的问题是此代码块之外的另一个端点,它没有设置 response_model_exclude_none=True。每个需要排除那些“无”值的端点都需要设置。

【讨论】:

    猜你喜欢
    • 2023-02-10
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多