Skip to content
8 changes: 6 additions & 2 deletions sqlmodel/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,9 +395,13 @@ def Field(
current_schema_extra = schema_extra or {}

if IS_PYDANTIC_V2:
current_schema_extra.update(pattern=pattern or regex)
current_schema_extra.update(
pattern=pattern or regex or current_schema_extra.get("pattern")
)
else:
current_schema_extra.update(regex=regex or pattern)
current_schema_extra.update(
regex=regex or pattern or current_schema_extra.get("pattern")
)

field_info = FieldInfo(
default,
Expand Down
12 changes: 6 additions & 6 deletions tests/test_pydantic/test_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,13 @@ class Model(SQLModel):
def test_field_regex_param(param: str):
class DateModel(SQLModel):
date_1: str = Field(**{param: r"^\d{2}-\d{2}-\d{4}$"})
date_2: str = Field(schema_extra={param: r"^\d{2}-\d{2}-\d{4}$"})

DateModel(date_1="12-31-2024", date_2="12-31-2024")
# Validates correctly
DateModel(date_1="12-31-2024") # Validates correctly

with pytest.raises(ValidationError):
DateModel(date_1="incorrect", date_2="12-31-2024") # date_1 pattern mismatch

def test_field_pattern_via_schema_extra():
class DateModel(SQLModel):
date_1: str = Field(schema_extra={"pattern": r"^\d{2}-\d{2}-\d{4}$"})

with pytest.raises(ValidationError):
DateModel(date_1="12-31-2024", date_2="incorrect") # date_2 pattern mismatch
DateModel(date_1="incorrect")
Loading