Pydantic

Published: by Creative Commons Licence

Base Model

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name = 'John Doe'
    age: int

The above code defines a base model with three attributes: id, name, and age. The id and age attributes are required, while the name attribute has a default value of John Doe.

Instantiating the model is as simple as passing in the required attributes:


user = User(id=1, age=25)

Optional


from typing import Optional

class User(BaseModel):
    id: int
    name: str
    age: Optional[int] = None

The code defines an optional age attribute. The attribute is optional because it has a default value of None.

Nested Models


from typing import List

class User(BaseModel):
    id: int
    name: str
    age: int

class Post(BaseModel):
    id: int
    title: str
    content: str
    writer: User

The code defines a Post model with a writer attribute of type User. The writer attribute is a nested model.

Validators


from pydantic import BaseModel, validator, ValidationError

class User(BaseModel):
    id: int
    name: str
    age: int

    @validator('age')
    def check_age(cls, v):
        if v < 18:
            raise ValidationError('must be 18 or older')
        return v

The code defines a validator for the age attribute. The validator checks if the age is greater than or equal to 18. If the age is less than 18, a ValidationError is raised.

Field


from pydantic import BaseModel, Field

class User(BaseModel):
    id: int = Field(..., gt=0)
    name: str = Field(..., min_length=3, description='Name of the user')
    age: int = Field(None, gt=0, lt=150)

The Field class is very useful when you want to add metadata to your model attributes. ... means required. gt means greater than. lt means less than. There are many other arguments you can pass to the Field class, such as description, title, alias, etc.