[BUG] Pydantic's StringConstraint not working as expected in SQLModel #1329
-
First Check
Commit to Help
Example Codefrom pydantic import BaseModel
from sqlmodel import SQLModel, Field
from typing_extensions import Annotated
from pydantic.types import StringConstraints
UsernameStr = Annotated[str, StringConstraints(strip_whitespace=True, to_lower=True)]
class NormalModel(BaseModel):
username: UsernameStr
class SqlModel(SQLModel, table=True):
id: str = Field(primary_key=True)
username: UsernameStr
print(f"Normal: {NormalModel(username='ABC')}")
print(f"Sql: {SqlModel(username='ABC')}") DescriptionThe expected output is:
where in both cases the username is in lower case. However, the output is:
Notice that pydantic converted the username to lower case while sqlmodel didnt. Operating SystemWindows Operating System DetailsNo response SQLModel Version0.0.24 Python Version3.10.0 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This is because of You can use But conventional approach is to use separate model\models for input and output data validation: from typing import Optional
from pydantic.types import StringConstraints
from sqlmodel import Field, SQLModel
from typing_extensions import Annotated
UsernameStr = Annotated[str, StringConstraints(strip_whitespace=True, to_lower=True)]
class SqlModelBase(SQLModel):
username: UsernameStr
class SqlModelCreate(SqlModelBase):
pass
class SqlModel(SqlModelBase, table=True):
id: Optional[str] = Field(default=None, primary_key=True)
a_input = SqlModelCreate(username='ABC')
a = SqlModel.model_validate(a_input)
print(f"Sql: {a}") # Sql: id=None username='abc' Read more: #52 (comment) |
Beta Was this translation helpful? Give feedback.
This is because of
table=True
. Such "table"-models bypass validation on instantiation.You can use
SqlModel.model_validate({"username": 'ABC'})
instead ofSqlModel(username='ABC')
.But conventional approach is to use separate model\models for input and output data validation: