1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Pydantic seperate schema validation from logic/functional validation

Discussão em 'Python' iniciado por Stack, Outubro 8, 2024.

  1. Stack

    Stack Membro Participativo

    Let's say I have this model:

    class User(BaseModel):
    name: str
    email: EmailStr
    phone_number: str
    job_title: str
    company: str
    salary: int

    @field_validator('company')
    def valid_company(cls, company: str) -> str:
    # validate that the company exists...
    return company


    However, I want to expose a way for the developer to be able to validate the schema vs the logic seperately.

    I thought of doing this:

    class User(BaseModel):
    name: str
    email: EmailStr
    phone_number: str
    job_title: str
    company: str
    salary: int

    class UserValidator(User):
    @field_validator('company')
    def valid_company(cls, company: str) -> str:
    # validate that the company exists...
    return company


    This way the developer can use User vs UserValidator to validate the schema vs the logic.

    However, the User model is being used in other models as well. So I kinda have to override some fields for some models like:

    class Account(BaseModel):
    user: User
    ...


    class AccountValidator(Account):
    user: UserValidator

    custom_validators...


    Is there a better way to do this? Maybe even using another library?

    Continue reading...

Compartilhe esta Página