Home > Enterprise >  How to set max_length for two fields combined in Pydantic
How to set max_length for two fields combined in Pydantic

Time:09-28

I know for a single field it can be done through constr something like:

class Email(BaseModel):
    local_part: EmailPartType[constr(max_length=255)]
    domain_part: EmailPartType[constr(max_length=255)]

But how can I set max_length for these two fields combined? Eventually, I can override my __init__ or my custom factory to implement this. But I want to know if there is a neater way in pydantic which is a new (and nice) thing to me.

CodePudding user response:

You can use root validator to validate multiple fields using a common condition:

from pydantic import constr, root_validator, BaseModel


class Email(BaseModel):
    local_part: str
    domain_part: str

    @root_validator
    def local_domain_len(cls, values):
        assert len(values['local_part'])   len(
            values['domain_part']) <= 255, 'Common local and domain length is greater than 255'
        return values
  • Related