diff --git a/docs/examples/exporting_models_json_forward_ref.py b/docs/examples/exporting_models_json_forward_ref.py index 540221f3a2d..c4a43cf0cc6 100644 --- a/docs/examples/exporting_models_json_forward_ref.py +++ b/docs/examples/exporting_models_json_forward_ref.py @@ -31,4 +31,4 @@ class Config: User(name='John', address=Address(city='London', country='UK')), ], ) -print(wolfgang.json()) +print(wolfgang.json(to_dict=False)) diff --git a/docs/usage/exporting_models.md b/docs/usage/exporting_models.md index f5770daa4f0..50ee7996943 100644 --- a/docs/usage/exporting_models.md +++ b/docs/usage/exporting_models.md @@ -109,6 +109,8 @@ _(This script is complete, it should run "as is")_ ### Serialising self-reference or other models +By default, models are serialised as dictionaries. +If you want to serialise them differently, you can add `to_dict=False` and add the classes of the model in `json_encoders`. In case of forward references, you can use a string with the class name instead of the class itself ```py {!.tmp_examples/exporting_models_json_forward_ref.py!} diff --git a/tests/test_json.py b/tests/test_json.py index 0c5973f1c1f..ed42025db9b 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -281,7 +281,7 @@ class Config: assert m.json() == '{\n "a": 1,\n "b": "foo"\n}' -def test_json_nested_encode(): +def test_json_nested_encode_models(): class Phone(BaseModel): manufacturer: str number: int @@ -314,11 +314,15 @@ class Config: timon.friend = pumbaa - assert iphone.json() == '{"manufacturer": "Apple", "number": 18002752273}' + assert iphone.json(to_dict=False) == '{"manufacturer": "Apple", "number": 18002752273}' assert ( - pumbaa.json() == '{"name": "Pumbaa", "SSN": 234, "birthday": 737424000.0, "phone": 18007267864, "friend": null}' + pumbaa.json(to_dict=False) + == '{"name": "Pumbaa", "SSN": 234, "birthday": 737424000.0, "phone": 18007267864, "friend": null}' + ) + assert ( + timon.json(to_dict=False) + == '{"name": "Timon", "SSN": 123, "birthday": 738892800.0, "phone": 18002752273, "friend": 234}' ) - assert timon.json() == '{"name": "Timon", "SSN": 123, "birthday": 738892800.0, "phone": 18002752273, "friend": 234}' def test_custom_encode_fallback_basemodel(): @@ -357,3 +361,11 @@ class Config: with pytest.raises(TypeError, match='not serialisable'): Foo(x=MyExoticType()).json(encoder=custom_encoder) + + +def test_recursive(): + class Model(BaseModel): + value: Optional[str] + nested: Optional[BaseModel] + + assert Model(value=None, nested=Model(value=None)).json(exclude_none=True) == '{"nested": {}}'