How to enable field validators in SQLModel #752
Unanswered
mohit2152sharma
asked this question in
Questions
Replies: 1 comment
-
I use from pydantic import EmailStr
from sqlmodel import Field, SQLModel
class User(SQLModel, table=True): # pyright: ignore
...
email: EmailStr = Field(
sa_type=String(), # type: ignore[call-overload]
unique=True,
index=True,
nullable=False,
description="The email of the user",
) and that gives me email validation from pydantic and in database it's a regular string or: from pydantic import IPvAnyNetwork
from sqlmodel import Field, SQLModel
from sqlalchemy import ARRAY, String
from sqlalchemy.sql.expression import false
class Token(SQLModel, table=True):
"""Token Model, represents the token for access to service APIs."""
...
internal: bool = Field(
sa_column_kwargs={"server_default": false()},
default=False,
description="Whether the token is an internal system token or not",
)
allowed_ips: list[IPvAnyNetwork] = Field(
sa_type=ARRAY(String), # type: ignore[call-overload]
default=[],
description="The list of allowed IPv4 or IPv6 addresses/subnets for the token",
) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
Description
Pydantic has a type
EmailStr
which can check for whether the string is a valid email or not. I have a column in my database for emails.When I use the following code:
sqlmodel complains with following error
I can do away with this error by using
sa_column
but that also drops the additional checks that pydantic provides on email string. For example:This runs, but it also considers
"abc"
as a valid email field.How can I have a custom type with validation rules in sql model? For example:
Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.14
Python Version
3.11.5
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions