Wednesday 13 October 2021

Pydantic: Define a model with required or mandatory fields

There are three ways to define a mandatory field.

a.   Using just type annotation

b.   Using ...

c.    Using Field(...)

 

model_with_mandatory_fields.py

from pydantic import BaseModel, Field, ValidationError

class Employee(BaseModel):
    id: int
    name: str = ...
    age: int = Field(...)

try:
    emp1 = Employee(name = 'Krishna', age = 23)
except ValidationError as e:
    print(e.json() + '\n\n')

try:
    emp1 = Employee(id=1, age = 23)
except ValidationError as e:
    print(e.json() + '\n\n')

try:
    emp1 = Employee(id = 1, name = 'Krishna')
except ValidationError as e:
    print(e.json() + '\n\n')

In the above example, id, name and age are mandatory fields.

 

Output

[
  {
    "loc": [
      "id"
    ],
    "msg": "field required",
    "type": "value_error.missing"
  }
]


[
  {
    "loc": [
      "name"
    ],
    "msg": "field required",
    "type": "value_error.missing"
  }
]


[
  {
    "loc": [
      "age"
    ],
    "msg": "field required",
    "type": "value_error.missing"
  }
]

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment