mirror of https://github.com/tiangolo/fastapi.git
🐛 Fix encoding a Pydantic model that inherits from another with json_encoders (#1769)
This commit is contained in:
parent
f63cec9c95
commit
7fbe3737bc
|
|
@ -48,7 +48,7 @@ def jsonable_encoder(
|
|||
if exclude is not None and not isinstance(exclude, set):
|
||||
exclude = set(exclude)
|
||||
if isinstance(obj, BaseModel):
|
||||
encoder = getattr(obj.Config, "json_encoders", {})
|
||||
encoder = getattr(obj.__config__, "json_encoders", {})
|
||||
if custom_encoder:
|
||||
encoder.update(custom_encoder)
|
||||
if PYDANTIC_1:
|
||||
|
|
|
|||
|
|
@ -55,6 +55,11 @@ class ModelWithCustomEncoder(BaseModel):
|
|||
}
|
||||
|
||||
|
||||
class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder):
|
||||
class Config:
|
||||
pass
|
||||
|
||||
|
||||
class RoleEnum(Enum):
|
||||
admin = "admin"
|
||||
normal = "normal"
|
||||
|
|
@ -117,6 +122,11 @@ def test_encode_custom_json_encoders_model():
|
|||
assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"}
|
||||
|
||||
|
||||
def test_encode_custom_json_encoders_model_subclass():
|
||||
model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8))
|
||||
assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"}
|
||||
|
||||
|
||||
def test_encode_model_with_config():
|
||||
model = ModelWithConfig(role=RoleEnum.admin)
|
||||
assert jsonable_encoder(model) == {"role": "admin"}
|
||||
|
|
|
|||
Loading…
Reference in New Issue