SQLModel with Pydantic validator

2.4k Views Asked by At

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?

1

There are 1 best solutions below

0
On

The UseCreate class does not have a class attribute named password, hence the error.

You probably meant to check if the repeat_password attribute is the same as the password attribute. You can achieve that with the root validator (The documentation even mentions this exact use case):

class UserBase(SQLModel):
    firstname: str
    lastname: str
    username: str
    email: str
    password: str
    age: int


class UserCreate(UserBase):
    repeat_password: str

    @root_validator
    def check_repeat_password(cls, values):
        pw1, pw2 = values.get("password"), values.get("repeat_password")
        if pw1 is not None and pw2 is not None and pw1 != pw2:
            raise ValueError("passwords do not match")
        return values

Moreover, don't throw HTTPException in the model validation layer. Use ValueError. Let the HTTP framework handle HTTP.