SQLModel's Field is needs to update the name of a param for compatibility with Pydantic. #2082
First Check
Example Codeimport re
import sqlmodel
ORCID_REGEX = re.compile(r"([\dX]{4}-[\dX]{4}-[\dX]{4}-[\dX]{4})")
class Author(sqlmodel.SQLModel, table=False):
name: str = sqlmodel.Field(description="The name of the author.")
orcid: Optional[str] = sqlmodel.Field(
default=None,
description="The author's ORCID iD, if available.",
regex=r"([\dX]{4}-[\dX]{4}-[\dX]{4}-[\dX]{4})"
)
def __repr__(self) -> str:
if self.orcid is None:
return f"Author({self.name})"
return f"Author({self.name}, orcid={self.orcid})"
def __hash__(self) -> int:
if self.orcid is not None:
return hash(self.orcid)
return hash(self.name)
def __eq__(self, other, /) -> bool:
if isinstance(other, str):
return self.name == other
elif not isinstance(other, self.__class__):
return False
if other.orcid is not None:
return self.orcid == other.orcid
return self.name == other.nameDescriptionPydantic's Field changed the parameter name of regex to pattern, so the value given to regex isn't being used by Pydantic. Operating SystemLinux Operating System DetailsDocker image base: Project Version0.0.38 Python Version3.14.4 Additional Contextpydantic==2.13.4 |
Replies: 2 comments
|
You are right about the compatibility gap. SQLModel's current Field overloads still expose regex, while Pydantic v2 uses pattern, so relying on regex here can fail to create the validation constraint you expect. Until SQLModel accepts and forwards pattern directly, a clean Pydantic-v2 workaround is to put the constraint on the type: define Orcid = Annotated[str, StringConstraints(pattern=r"^[\dX]{4}-[\dX]{4}-[\dX]{4}-[\dX]{4}$")] and annotate the field as orcid: Orcid | None = Field(default=None, description=...). Anchoring the expression is also important; otherwise a valid-looking substring inside a longer invalid value can match. This keeps runtime validation and generated JSON Schema aligned without depending on SQLModel's legacy regex parameter. The long-term fix should add pattern to SQLModel Field's overloads and implementation, pass it to Pydantic FieldInfo, and deprecate regex in a version-compatible way rather than silently renaming it, since existing applications may still depend on the old argument. |
|
We already have PR for this: #1231 |
We already have PR for this: #1231
It's awaiting Sebastian's review