I want to use SQLModel
which combines pydantic and SQLAlchemy.
I have a UserCreate
class, which should use a custom validator.
This is my Code:
class UserBase(SQLModel):
firstname: str
lastname: str
username: str
email: str
password: str
age: int
class UserCreate(UserBase):
repeat_password: str
@validator("repeat_password")
def check_repeat_password(cls, value):
if value != cls.password:
raise HTTPException(
status_code=400,
detail="Repeat password does not match password."
)
return value
class UserTable(UserBase, table=True):
__tablename__ = "users"
id: Optional[int] = Field(default=None, primary_key=True)
This results in the following error:
line 44, in check_repeat_password
if value != cls.password:
AttributeError: type object 'UserCreate' has no attribute 'password'
Can anyone help me? How can I apply a custom validator when I use the SQLModel
Library?
The
UseCreate
class does not have a class attribute namedpassword
, hence the error.You probably meant to check if the
repeat_password
attribute is the same as thepassword
attribute. You can achieve that with the root validator (The documentation even mentions this exact use case):Moreover, don't throw
HTTPException
in the model validation layer. UseValueError
. Let the HTTP framework handle HTTP.