python type_error ai_generated true

AttributeError: 'Query' 对象没有属性 'default'。

AttributeError: 'Query' object has no attribute 'default'

ID: python/fastapi-attribute-error-no-attribute-query

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2025-01-09首次发现

版本兼容性

版本状态引入弃用备注
0.95.x active — — —
0.100.x active — — —

根因分析

在 Pydantic v2 / FastAPI 版本中使用了已重命名的参数,或错误地将 `Query()` 与 `Annotated` 混用。

English

Using `Query(default=...)` in a Pydantic v2 / FastAPI version where the parameter was renamed to `default` only in newer releases, or mixing `Query()` with `Annotated` incorrectly.

generic

解决方案

  1. 95% 成功率
    Use the modern form: `q: Annotated[str | None, Query(max_length=50)] = None`
  2. 90% 成功率
    Or the older positional style: `q: str = Query(None, max_length=50)` (no `default=` keyword).

无效尝试

常见但无效的做法:

  1. 80% 失败

    Downgrade breaks Pydantic v2 compatibility and other features.

  2. 90% 失败

    Fragile across versions and breaks OpenAPI generation.