mirror of
https://github.com/fastapi/fastapi.git
synced 2026-04-08 09:00:26 -04:00
🐛 Fix skip_defaults implementation when returning a Pydantic model (#422)
This commit is contained in:
committed by
Sebastián Ramírez
parent
b77a43bcac
commit
38495fffa5
@@ -52,6 +52,8 @@ def serialize_response(
|
||||
errors.extend(errors_)
|
||||
if errors:
|
||||
raise ValidationError(errors)
|
||||
if skip_defaults and isinstance(response, BaseModel):
|
||||
value = response.dict(skip_defaults=skip_defaults)
|
||||
return jsonable_encoder(
|
||||
value,
|
||||
include=include,
|
||||
|
||||
29
tests/test_skip_defaults.py
Normal file
29
tests/test_skip_defaults.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
class SubModel(BaseModel):
|
||||
a: Optional[str] = "foo"
|
||||
|
||||
|
||||
class Model(BaseModel):
|
||||
x: Optional[int]
|
||||
sub: SubModel
|
||||
|
||||
|
||||
@app.get("/", response_model=Model, response_model_skip_defaults=True)
|
||||
def get() -> Model:
|
||||
return Model(sub={})
|
||||
|
||||
|
||||
client = TestClient(app)
|
||||
|
||||
|
||||
def test_return_defaults():
|
||||
response = client.get("/")
|
||||
assert response.json() == {"sub": {}}
|
||||
Reference in New Issue
Block a user