Skip to content

Commit

Permalink
put back old behaviour and add to_dict
Browse files Browse the repository at this point in the history
  • Loading branch information
PrettyWood committed Dec 20, 2021
1 parent 5da5ee0 commit 1a8205b
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
2 changes: 1 addition & 1 deletion docs/examples/exporting_models_json_forward_ref.py
Expand Up @@ -31,4 +31,4 @@ class Config:
User(name='John', address=Address(city='London', country='UK')),
],
)
print(wolfgang.json())
print(wolfgang.json(to_dict=False))
2 changes: 2 additions & 0 deletions docs/usage/exporting_models.md
Expand Up @@ -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!}
Expand Down
20 changes: 16 additions & 4 deletions tests/test_json.py
Expand Up @@ -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
Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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": {}}'

0 comments on commit 1a8205b

Please sign in to comment.