Files
pydantic/docs/examples/exporting_models_json_forward_ref.py
T
Eric Jolibois edad0dbc46 fix: keep old behaviour of json() by default (#3542)
* fix: handle basemodel fallback for custom encoders

* put back old behaviour and add to_dict

* typo

Co-authored-by: Christian Bundy <christianbundy@fraction.io>

Co-authored-by: Christian Bundy <christianbundy@fraction.io>
2021-12-24 13:14:13 +00:00

35 lines
816 B
Python

from typing import List, Optional
from pydantic import BaseModel
class Address(BaseModel):
city: str
country: str
class User(BaseModel):
name: str
address: Address
friends: Optional[List['User']] = None
class Config:
json_encoders = {
Address: lambda a: f'{a.city} ({a.country})',
'User': lambda u: f'{u.name} in {u.address.city} '
f'({u.address.country[:2].upper()})',
}
User.update_forward_refs()
wolfgang = User(
name='Wolfgang',
address=Address(city='Berlin', country='Deutschland'),
friends=[
User(name='Pierre', address=Address(city='Paris', country='France')),
User(name='John', address=Address(city='London', country='UK')),
],
)
print(wolfgang.json(models_as_dict=False))