]> git.ipfire.org Git - thirdparty/fastapi/sqlmodel.git/commitdiff
🐛 Fix handling validators for non-default values (#253)
authorbyrman <carsten.byrman@nelen-schuurmans.nl>
Sat, 27 Aug 2022 23:10:23 +0000 (01:10 +0200)
committerGitHub <noreply@github.com>
Sat, 27 Aug 2022 23:10:23 +0000 (23:10 +0000)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
sqlmodel/main.py
tests/test_validation.py [new file with mode: 0644]

index 8af077dafec0fce3e5b6c642b1893a82adf5a2ed..0144f6f4aae62d02999059bb31ab9672997142cf 100644 (file)
@@ -582,7 +582,7 @@ class SQLModel(BaseModel, metaclass=SQLModelMetaclass, registry=default_registry
             values, fields_set, validation_error = validate_model(cls, value)
             if validation_error:
                 raise validation_error
-            model = cls(**values)
+            model = cls(**value)
             # Reset fields set, this would have been done in Pydantic in __init__
             object.__setattr__(model, "__fields_set__", fields_set)
             return model
diff --git a/tests/test_validation.py b/tests/test_validation.py
new file mode 100644 (file)
index 0000000..a3ff6e3
--- /dev/null
@@ -0,0 +1,33 @@
+from typing import Optional
+
+import pytest
+from pydantic import validator
+from pydantic.error_wrappers import ValidationError
+from sqlmodel import SQLModel
+
+
+def test_validation(clear_sqlmodel):
+    """Test validation of implicit and explict None values.
+
+    # For consistency with pydantic, validators are not to be called on
+    # arguments that are not explicitly provided.
+
+    https://github.com/tiangolo/sqlmodel/issues/230
+    https://github.com/samuelcolvin/pydantic/issues/1223
+
+    """
+
+    class Hero(SQLModel):
+        name: Optional[str] = None
+        secret_name: Optional[str] = None
+        age: Optional[int] = None
+
+        @validator("name", "secret_name", "age")
+        def reject_none(cls, v):
+            assert v is not None
+            return v
+
+    Hero.validate({"age": 25})
+
+    with pytest.raises(ValidationError):
+        Hero.validate({"name": None, "age": 25})