Search code examples
pythontypesconditional-statementspydantic

Create Python Data Models with conditions


How do I create pydantic model with conditions?

I have a pydantic model. It works well when declaring new class with this model as base. The problem I have is, the

  • BaseUser.username should have
    • maxlength of 32 chars
    • minlength of 6 chars.
  • BaseUser.password to be fixed to 64 chars. Not less, not more.

Is that any way that I can achieve it through datatypes?

> I know that I can do it with simple "if" statements, but I want it to be a datatype in pydantic model.

from pydantic import BaseModel

class BaseUser(BaseModel):
    id: int
    username: str
    password: str
Thank you.

Solution

  • Have you considered using Contraint types?

    from pydantic import BaseModel, constr
    
    class BaseUser(BaseModel):
        id: int
        username: constr(min_length=6, max_length=32)
        password: constr(min_length=64, max_length=64)
    

    Sample output

    >>> user = BaseUser(id='1', username='foo', password='4m*PbpA!*A2XUdvU@u0WTvvFRyNSMcndVm6@NkZwJR1afBb@G1i5*1vvh9z*g8xw'
    
    ValidationError: 1 validation error for BaseUser
    username
      ensure this value has at least 6 characters (type=value_error.any_str.min_length; limit_value=6)
    
    
    >> user = BaseUser(id='1', username='foobar', password='4m*PbpA!*A2XU')
    
    ValidationError: 1 validation error for BaseUser
    password
      ensure this value has at least 64 characters (type=value_error.any_str.min_length; limit_value=64)
    
    >>> user = BaseUser(id='1', username='foobar', password='4m*PbpA!*A2XUdvU@u0WTvvFRyNSMcndVm6@NkZwJR1afBb@G1i5*1vvh9z*g8xw')
    
    >>> user.dict()
    >>> 
    {'id': 1,
     'username': 'foobar',
     'password': '4m*PbpA!*A2XUdvU@u0WTvvFRyNSMcndVm6@NkZwJR1afBb@G1i5*1vvh9z*g8xw'}
    

    Just a heads-up: I have never used Pydantic before. So, there could be a better way to solve this.