BaşlayınÜcretsiz başlayın

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.

Bu egzersiz, kursun bir parçasıdır

Deploying AI into Production with FastAPI

Kursa Göz Atın

Egzersiz talimatları

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

Uygulamalı etkileşimli egzersiz

Bu egzersizi bu örnek kodu tamamlayarak deneyin.

# 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)
Kodu Düzenle ve Çalıştır