|
| 1 | +from typing import Any |
| 2 | +from pydantic import field_validator, model_validator, ConfigDict, BaseModel, Field |
| 3 | + |
| 4 | + |
| 5 | +class ExampleModel(BaseModel): |
| 6 | + """An example model.""" |
| 7 | + |
| 8 | + model_config = ConfigDict(frozen=False) |
| 9 | + |
| 10 | + field_without_default: str |
| 11 | + """Shows the *[Required]* marker in the signature.""" |
| 12 | + |
| 13 | + field_plain_with_validator: int = 100 |
| 14 | + """Show standard field with type annotation.""" |
| 15 | + |
| 16 | + field_with_validator_and_alias: str = Field("FooBar", alias="BarFoo", validation_alias="BarFoo") |
| 17 | + """Shows corresponding validator with link/anchor.""" |
| 18 | + |
| 19 | + field_with_constraints_and_description: int = Field( |
| 20 | + default=5, ge=0, le=100, description="Shows constraints within doc string." |
| 21 | + ) |
| 22 | + |
| 23 | + @field_validator("field_with_validator_and_alias", "field_without_default", mode="before") |
| 24 | + @classmethod |
| 25 | + def check_max_length_ten(cls, v) -> str: |
| 26 | + """Show corresponding field with link/anchor.""" |
| 27 | + if len(v) >= 10: |
| 28 | + raise ValueError("No more than 10 characters allowed") |
| 29 | + return v |
| 30 | + |
| 31 | + @model_validator(mode="before") |
| 32 | + @classmethod |
| 33 | + def lowercase_only(cls, data: dict[str, Any]) -> dict[str, Any]: |
| 34 | + """Ensure that the field without a default is lowercase.""" |
| 35 | + if isinstance(data.get("field_without_default"), str): |
| 36 | + data["field_without_default"] = data["field_without_default"].lower() |
| 37 | + return data |
0 commit comments