IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Deploying AI into Production with FastAPI

Visualizza il corso

Istruzioni dell'esercizio

  • 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.

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

# 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)
Modifica ed esegui il codice