From: Patrick Wang Date: Sat, 13 Jun 2020 17:20:11 +0000 (-0400) Subject: ✨ When using Pydantic models with __root__ use the internal value in jsonable_encoder... X-Git-Tag: 0.57.0~9 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=8fb755703d34b4d2ae30fd8d5d2bdc8d6983939d;p=thirdparty%2Ffastapi%2Ffastapi.git ✨ When using Pydantic models with __root__ use the internal value in jsonable_encoder (#1524) --- diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 26ceb21445..3f5b79d9eb 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -71,6 +71,8 @@ def jsonable_encoder( by_alias=by_alias, skip_defaults=bool(exclude_unset or skip_defaults), ) + if "__root__" in obj_dict: + obj_dict = obj_dict["__root__"] return jsonable_encoder( obj_dict, exclude_none=exclude_none, diff --git a/tests/test_jsonable_encoder.py b/tests/test_jsonable_encoder.py index adee443a89..d4ae344421 100644 --- a/tests/test_jsonable_encoder.py +++ b/tests/test_jsonable_encoder.py @@ -76,6 +76,10 @@ class ModelWithDefault(BaseModel): bla: str = "bla" +class ModelWithRoot(BaseModel): + __root__: str + + @pytest.fixture( name="model_with_path", params=[PurePath, PurePosixPath, PureWindowsPath] ) @@ -158,3 +162,8 @@ def test_encode_model_with_path(model_with_path): else: expected = "/foo/bar" assert jsonable_encoder(model_with_path) == {"path": expected} + + +def test_encode_root(): + model = ModelWithRoot(__root__="Foo") + assert jsonable_encoder(model) == "Foo"