Files
pydantic/docs/examples/exporting_models_json_subclass.py
T
Stephen Brown II cab6313798 Allow subclasses of known types to be encoded with superclass encoder (#1291)
* Add (failing) test for Subclass JSON encoding

* Allow subclasses of known types to be encoded with superclass encoder

* Add change file

* Add documentation, fix custom json_encoders and add unit test

Blacken doc
Fix test that worked on my machine
datetime.timestamp() is flakey?
Single quotes only

* Reduce lookups

- Remove last element in `__mro__` as it will always be `object`
- Use .get for compactness

* Regarding the loop

* Move Path and Enum into ENCODERS_BY_TYPE

Sort ENCODERS_BY_TYPE

* improve JSON docs

Co-authored-by: Samuel Colvin <s@muelcolvin.com>
2020-04-18 17:11:00 +01:00

24 lines
589 B
Python

from datetime import date, timedelta
from pydantic import BaseModel
from pydantic.validators import int_validator
class DayThisYear(date):
"""
Contrived example of a special type of date that
takes an int and interprets it as a day in the current year
"""
@classmethod
def __get_validators__(cls):
yield int_validator
yield cls.validate
@classmethod
def validate(cls, v: int):
return date.today().replace(month=1, day=1) + timedelta(days=v)
class FooModel(BaseModel):
date: DayThisYear
m = FooModel(date=300)
print(m.json())