Aan de slagGa gratis aan de slag

Field validation

You are building on the user comment moderation service. Your goal is to create a Pydantic User model that ensures data integrity across all users.

Implement validations for the username (min 5, max 50 characters) field.

Use Pydantic's Field class to add these constraints, and test your model with both valid and invalid product data to ensure it correctly handles various scenarios.

Deze oefening maakt deel uit van de cursus

Deploying AI into Production with FastAPI

Cursus bekijken

Oefeninstructies

  • Import the base model and field classes from Pydantic.
  • Inherit Pydantic's base model in the User model.
  • Add field validations on username attribute in the User class to have at least 5 characters and no more than 20 characters.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# Import the base model and field validator from Pydantic
from pydantic import ____, ____

# Inherit Pydantic's base model
class User(____): 
    # Set minimum and maximum name length
    username: str = ____(..., ____=5, ____=20)
    email: str
    age: int

user = User(username="john_doe", email="[email protected]", age=25)
print(user)
Code bewerken en uitvoeren