mirror of https://github.com/tiangolo/fastapi.git
🐛 Fix skip_defaults implementation when returning a Pydantic model (#422)
This commit is contained in:
parent
b77a43bcac
commit
38495fffa5
|
|
@ -52,6 +52,8 @@ def serialize_response(
|
||||||
errors.extend(errors_)
|
errors.extend(errors_)
|
||||||
if errors:
|
if errors:
|
||||||
raise ValidationError(errors)
|
raise ValidationError(errors)
|
||||||
|
if skip_defaults and isinstance(response, BaseModel):
|
||||||
|
value = response.dict(skip_defaults=skip_defaults)
|
||||||
return jsonable_encoder(
|
return jsonable_encoder(
|
||||||
value,
|
value,
|
||||||
include=include,
|
include=include,
|
||||||
|
|
|
||||||
|
|
@ -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": {}}
|
||||||
Loading…
Reference in New Issue