Search code examples
pythonfastapipydantic

Validation for multiple fields on pydantic BaseModel


In my fastapi app I have created a pydantic BaseModel with two fields (among others): 'relation_type' and 'document_list' (both are optional). I want to validate that, if 'relation_type' has a value, then, 'document_list' must have al least one element. Otherwise it will show a Validation error. How can I do it?

class TipoRelacionEnum(str, Enum):
    nota_credito = "01"
    nota_debito = "02"
    devolucion_mercancias = "03"
    sustitucion = "04"
    traslado = "05"
    facturacion_generada = "06"
    anticipo = "07"

class Cfdi(BaseModel):
    relation_type: Optional[Annotated[TipoRelacionEnum, Field(title="Tipo de Relación",
                                                                description="""Se debe registrar la clave de la relación que existe entre este
                                                                                comprobante que se está generando y el o los CFDI previos.""",
                                                                examples=[
                                                                    "04",
                                                                    "01",
                                                                ],
                                                                max_length=2)]] = None

    document_list: list[str] | None = None

Solution

  • Yes, you can use model_validator for that

    from pydantic import BaseModel, model_validator
    from typing import Optional
    
    
    class Cfdi(BaseModel):
        relation_type: Optional[...] = None
        document_list: Optional[list[str]] = None
        
        @model_validator(mode="after")
        @classmethod
        def check_two_fields_together(cls, data: dict) -> dict:
            if relation_type and len(document_list) < 1:
                raise ValueError("Error text")
            return data