Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

300
Vistas
Pydantic validator does not work as expected

I have recently found the power of Pydantic validators and proceeded to uses them in one of my personal projects.

However, I've encountered a problem: the failure of one validator does not stop the execution of the following validators, resulting in an Exception.

class Field(BaseModel):
    name: constr(min_length=1, max_length=32)
    type: constr(min_length=1, max_length=32)
    length: Optional[int]
    nullable: bool


class Unique(BaseModel):
    name: constr(min_length=1, max_length=32)
    unique_fields: List[constr(min_length=1, max_length=32)]


class Resource(BaseModel):
    name: constr(min_length=1, max_length=32)
    table_name: constr(min_length=1, max_length=32)
    fields: List[Field]
    primary_key: constr(min_length=1, max_length=32)
    uniques: Optional[List[Unique]]

    @validator('name')
    def resource_name_must_be_pure_string(cls, v):
        if not v.isalpha():
            raise ValueError(ONLY_ALPHA_ERR.format("Resource name"))
        return v

    @validator('table_name')
    def table_name_must_be_pure_string(cls, v):
        if not v.isalpha():
            raise ValueError(ONLY_ALPHA_ERR.format("Table name"))
        return v

    @validator('fields', pre=True)
    def field_name_must_be_pure_string(cls, v):
        fieldnames = [field["name"] for field in v]
        print(fieldnames)
        for fieldname in fieldnames:
            if not fieldname.replace('_', '').isalpha():
                print('was here')
                raise ValueError("A field's name can only contain alphabetic characters and '_'.")
        return v

    @validator('primary_key')
    def primary_key_must_be_in_fields(cls, v, values):
        fieldnames = [field.name for field in values["fields"]]

        if v not in fieldnames:
            raise ValueError(f"Primary key `{v}` should be one of the input fields.")
        return v

The method field_name_must_be_pure_string prints "was here", therefore the ValueError exception should have been raised, but the execution proceeds to the next validator, which would be primary_key_must_be_in_fields, that fails because the preceding list of fields was invalid.

What would be the solution to this corner case?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Late answer, but managed to avoid getting a crash by using the following:

@validator('primary_key')
def primary_key_must_be_in_fields(cls, v, values):
    if "fields" not in values:
        return

    fieldnames = [field.name for field in values["fields"]]

    if v not in fieldnames:
        raise ValueError(f"Primary key `{v}` should be one of the input fields.")
    return v

It took a while to realise that Pydantic will do all validations and will not stop at first exception.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda