CodeBlanks Logo Icon CodeBlanks

Field

Learn validation rules with Field(...).

Field

Field(...) adds validation rules to a field. With gt, lt, ge, le you set bounds; with min_length and max_length you set length.

from pydantic import BaseModel, Field

class User(BaseModel):
    name: str = Field(min_length=2)
    age: int = Field(gt=0, lt=200)

gt=0 means the value must be greater than zero; lt=200 means less than 200. If a rule is broken, Pydantic raises.

Bounds and length

For numeric fields, use gt (greater than), lt (less than), ge (greater or equal), le (less or equal). For string fields, min_length and max_length limit length.

age: int = Field(ge=18, le=65)        # between 18-65
name: str = Field(min_length=2, max_length=50)  # 2-50 chars
tags: list = Field(min_length=1)      # at least one item

These rules prevent bad data from entering the system; they are especially useful in APIs.

Practice User model with Field rules

Start with from pydantic import BaseModel, Field. Define class User(BaseModel):. Add fields name: str = Field(min_length=2) and age: int = Field(gt=0, lt=200). Create an instance with u = User(name="Ayşe", age=30). Print the values with print(u.name, u.age).

Starter code

main.py
# bring in BaseModel and Field from pydantic
# define User class (derive from BaseModel)
# add a min length of 2 to name, a bound of zero and 200 to age
# create a User instance (Ayşe, 30)
# print the values

Sample solution

main.py
from pydantic import BaseModel, Field

class User(BaseModel):
    name: str = Field(min_length=2)
    age: int = Field(gt=0, lt=200)

u = User(name="Ayşe", age=30)
print(u.name, u.age)

Expected output

Ayşe 30

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the Field call

Question
from pydantic import BaseModel, Field

class User(BaseModel):
    age: int = ____(gt=0, lt=200)
Answer
from pydantic import BaseModel, Field

class User(BaseModel):
    age: int = Field(gt=0, lt=200)

Explanation: Field(gt=0, lt=200) sets bounds.

2 What does the Field(gt=0) rule mean?

  • The value must be greater than zero Correct answer
  • The value must be negative
  • The value must equal zero
  • The value cannot be zero

Explanation: gt=0 means the value must be greater than zero.

3 Match the Field concepts

Term Meaning
gt=0 Greater than zero
lt=200 Less than 200
min_length=2 At least 2 chars
max_length=50 At most 50 chars

All lessons in Advanced