mirror of
https://github.com/kennethreitz/pydantic.git
synced 2026-06-05 23:00:18 +00:00
b42fae081c
* add nested json encoding * fix timezones * add changes doc * split tests and rename example * Update changes/3941-lilyminium.md Co-authored-by: Samuel Colvin <samcolvin@gmail.com> * split tests into functions Co-authored-by: Samuel Colvin <samcolvin@gmail.com> Co-authored-by: Samuel Colvin <s@muelcolvin.com>
42 lines
1.1 KiB
Python
42 lines
1.1 KiB
Python
from datetime import datetime, timedelta
|
|
from pydantic import BaseModel
|
|
from pydantic.json import timedelta_isoformat
|
|
|
|
|
|
class CustomChildModel(BaseModel):
|
|
dt: datetime
|
|
diff: timedelta
|
|
|
|
class Config:
|
|
json_encoders = {
|
|
datetime: lambda v: v.timestamp(),
|
|
timedelta: timedelta_isoformat,
|
|
}
|
|
|
|
|
|
class ParentModel(BaseModel):
|
|
diff: timedelta
|
|
child: CustomChildModel
|
|
|
|
class Config:
|
|
json_encoders = {
|
|
timedelta: lambda v: v.total_seconds(),
|
|
CustomChildModel: lambda _: 'using parent encoder',
|
|
}
|
|
|
|
|
|
child = CustomChildModel(dt=datetime(2032, 6, 1), diff=timedelta(hours=100))
|
|
parent = ParentModel(diff=timedelta(hours=3), child=child)
|
|
|
|
# default encoder uses total_seconds() for diff
|
|
print(parent.json())
|
|
|
|
# nested encoder uses isoformat
|
|
print(parent.json(use_nested_encoders=True))
|
|
|
|
# turning off models_as_dict only uses the top-level formatter, however
|
|
|
|
print(parent.json(models_as_dict=False, use_nested_encoders=True))
|
|
|
|
print(parent.json(models_as_dict=False, use_nested_encoders=False))
|