on-internet
← Community

Pydantic- avoid duplicating validation logic for create and update models

Stack Overflow ·

I'm building a REST API using FastAPI and Pydantic. This is an example for my problem: class RestaurantCreate(BaseModel): name: str email: EmailStr max_tables: int @field_validator("max_tables") @classmethod def validate_tables(cls, v): if v <= 0: raise ValueError("must be positive") return v class RestaurantUpdate(BaseModel): name: Optional[str] = None email: Optional[EmailStr] = None max_tables: Optional[int] = None @field_validator("max_tables") @classmethod def validate_tables(cls, v): if v is not None and v <= 0: raise ValueError("must be positive") return v In general, I have two schemas

Comments

Sign in or sign up to comment and upvote.

No comments yet.