🐛 Fix handling validators for non-default values (#253)

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
This commit is contained in:
byrman 2022-08-28 01:10:23 +02:00 committed by GitHub
parent 71d6fcc31b
commit d380736043
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 1 deletions

View File

@ -582,7 +582,7 @@ class SQLModel(BaseModel, metaclass=SQLModelMetaclass, registry=default_registry
values, fields_set, validation_error = validate_model(cls, value) values, fields_set, validation_error = validate_model(cls, value)
if validation_error: if validation_error:
raise validation_error raise validation_error
model = cls(**values) model = cls(**value)
# Reset fields set, this would have been done in Pydantic in __init__ # Reset fields set, this would have been done in Pydantic in __init__
object.__setattr__(model, "__fields_set__", fields_set) object.__setattr__(model, "__fields_set__", fields_set)
return model return model

33
tests/test_validation.py Normal file
View File

@ -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})