Skip to content

Commit d380736

Browse files
byrmantiangolo
andauthored
🐛 Fix handling validators for non-default values (#253)
Co-authored-by: Sebastián Ramírez <[email protected]>
1 parent 71d6fcc commit d380736

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

sqlmodel/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,7 @@ def validate(cls: Type["SQLModel"], value: Any) -> "SQLModel":
582582
values, fields_set, validation_error = validate_model(cls, value)
583583
if validation_error:
584584
raise validation_error
585-
model = cls(**values)
585+
model = cls(**value)
586586
# Reset fields set, this would have been done in Pydantic in __init__
587587
object.__setattr__(model, "__fields_set__", fields_set)
588588
return model

tests/test_validation.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from typing import Optional
2+
3+
import pytest
4+
from pydantic import validator
5+
from pydantic.error_wrappers import ValidationError
6+
from sqlmodel import SQLModel
7+
8+
9+
def test_validation(clear_sqlmodel):
10+
"""Test validation of implicit and explict None values.
11+
12+
# For consistency with pydantic, validators are not to be called on
13+
# arguments that are not explicitly provided.
14+
15+
https://github.com/tiangolo/sqlmodel/issues/230
16+
https://github.com/samuelcolvin/pydantic/issues/1223
17+
18+
"""
19+
20+
class Hero(SQLModel):
21+
name: Optional[str] = None
22+
secret_name: Optional[str] = None
23+
age: Optional[int] = None
24+
25+
@validator("name", "secret_name", "age")
26+
def reject_none(cls, v):
27+
assert v is not None
28+
return v
29+
30+
Hero.validate({"age": 25})
31+
32+
with pytest.raises(ValidationError):
33+
Hero.validate({"name": None, "age": 25})

0 commit comments

Comments
 (0)