Pydantic User Model with Age Validation and Random Generation

  • Share this:

Code introduction


This code defines a Pydantic model named User with fields for name, age, and an optional email. It uses a validator to ensure the age is not negative. Then, it defines a function to generate a random user.


Technology Stack : Pydantic, Python Standard Library

Code Type : Pydantic Model and Validator

Code Difficulty : Intermediate


                
                    
from pydantic import BaseModel, validator
from typing import Optional
import random

class User(BaseModel):
    name: str
    age: int
    email: Optional[str] = None

    @validator('age')
    def check_age(cls, v):
        if v < 0:
            raise ValueError("Age cannot be negative")
        return v

def generate_random_user():
    names = ["Alice", "Bob", "Charlie", "David", "Eve"]
    age = random.randint(18, 100)
    email = f"{random.choice(names)}{random.randint(1, 1000)}@example.com" if random.choice([True, False]) else None
    return User(name=random.choice(names), age=age, email=email)