]> git.ipfire.org Git - thirdparty/fastapi/fastapi.git/commitdiff
🐛 Fix encoding a Pydantic model that inherits from another with json_encoders (#1769)
authorHenry Betts <henry.betts@btconnect.com>
Mon, 3 Aug 2020 15:24:29 +0000 (16:24 +0100)
committerGitHub <noreply@github.com>
Mon, 3 Aug 2020 15:24:29 +0000 (17:24 +0200)
fastapi/encoders.py
tests/test_jsonable_encoder.py

index a1b68829aefdc0264af6ab16816c41e66be0d9ec..d0d094b6a6b3aade6f0950b9d301b4b4a06c0a00 100644 (file)
@@ -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:
index 2514edfde9b26f506682a588c83e14b6e60456de..502f5f04c2689627f8b546c75692c4bba8058a6f 100644 (file)
@@ -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"}