Replies: 2 comments 1 reply
-
|
Verified this problem in Python 3.10.11, pydantic 1.10.18, and fastapi 0.95.2 (and uvicorn 0.31.0 in case it matters). Also verified this problem still exists when updating to Python 3.12.7, pydantic 2.9.2, and fastapi 0.115.0 (and uvicorn 0.31.0 still). I also tried calling I also tried by setting I could be wrong, but in my limited experience from what I can tell this looks like a Pydantic issue? |
Beta Was this translation helpful? Give feedback.
-
My attempt to explain why it doesn't work:DetailsWhen you use the syntax like model_depends_annotated: Annotated[TestModel, Depends(TestModel)]or model_depends_non_annotated: TestModel = Depends()it's actually the same as: model_depends_annotated: Annotated[TestModel, Depends(TestModel.__init__)]where def TestModel.__init__(self, field_true: bool | None = Field(True)):
self.field_true = field_trueFastAPI further analyzes the signature of So, for FastAPI it's equal to the following code: async def get_test_model(field_true: bool | None = Field(True)):
return TestModel(field_true=field_true)
@app.get("/test-unset")
def test_unset(model_depends_annotated: Annotated[TestModel, Depends(get_test_model)]):
passAs you can see, FastAPI will first validate the Since it's set explicitly, you can't exclude it with Current situationIn FastAPI from typing import Annotated
from pydantic import BaseModel, Field
from fastapi import FastAPI, Query
app = FastAPI()
class TestModel(BaseModel):
field_true: bool | None = Field(True)
@app.get("/test-unset")
def test_unset(
model_query: Annotated[TestModel, Query()],
):
return {
"model_query": model_query.model_dump(
exclude_unset=True,
),
}But it still doesn't work as expected (unset values are not excluded): |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
python -m uvicorn --host 0.0.0.0 --port 8080 app:apphttp://localhost:8080/test-unset{ "model_depends_annotated": {"field_true": true}, "model_depends_non_annotated": {"field_true": true}, "model_non_depends": {} }{ "model_depends_annotated": {}, "model_depends_non_annotated": {}, "model_non_depends": {} }Operating System
macOS
Operating System Details
No response
FastAPI Version
0.95.2
Python Version
Python 3.10.8
Additional Context
It could be related to #5891, but the same result if I make
test_unsetan async function.Beta Was this translation helpful? Give feedback.
All reactions