mirror of
https://github.com/fastapi/sqlmodel.git
synced 2026-01-05 17:09:42 -06:00
✨ Add support for Pydantic v2 (while keeping support for v1 if v2 is not available), including initial work by AntonDeMeester (#722)
Co-authored-by: Mohamed Farahat <farahats9@yahoo.com> Co-authored-by: Stefan Borer <stefan.borer@gmail.com> Co-authored-by: Peter Landry <peter.landry@gmail.com> Co-authored-by: Anton De Meester <antondemeester+github@gmail.com>
This commit is contained in:
committed by
GitHub
parent
5b733b348d
commit
fa2f178b8a
@@ -1,12 +1,14 @@
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
from pydantic import validator
|
||||
from pydantic.error_wrappers import ValidationError
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
from .conftest import needs_pydanticv1, needs_pydanticv2
|
||||
|
||||
def test_validation(clear_sqlmodel):
|
||||
|
||||
@needs_pydanticv1
|
||||
def test_validation_pydantic_v1(clear_sqlmodel):
|
||||
"""Test validation of implicit and explicit None values.
|
||||
|
||||
# For consistency with pydantic, validators are not to be called on
|
||||
@@ -16,6 +18,7 @@ def test_validation(clear_sqlmodel):
|
||||
https://github.com/samuelcolvin/pydantic/issues/1223
|
||||
|
||||
"""
|
||||
from pydantic import validator
|
||||
|
||||
class Hero(SQLModel):
|
||||
name: Optional[str] = None
|
||||
@@ -31,3 +34,32 @@ def test_validation(clear_sqlmodel):
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
Hero.validate({"name": None, "age": 25})
|
||||
|
||||
|
||||
@needs_pydanticv2
|
||||
def test_validation_pydantic_v2(clear_sqlmodel):
|
||||
"""Test validation of implicit and explicit 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
|
||||
|
||||
"""
|
||||
from pydantic import field_validator
|
||||
|
||||
class Hero(SQLModel):
|
||||
name: Optional[str] = None
|
||||
secret_name: Optional[str] = None
|
||||
age: Optional[int] = None
|
||||
|
||||
@field_validator("name", "secret_name", "age")
|
||||
def reject_none(cls, v):
|
||||
assert v is not None
|
||||
return v
|
||||
|
||||
Hero.model_validate({"age": 25})
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
Hero.model_validate({"name": None, "age": 25})
|
||||
|
||||
Reference in New Issue
Block a user