Files
pydantic/docs/examples/schema_unenforced_constraints.py
⬢ Samuel Colvin ef8f9fe51b Uprev all dependencies (#4955)
* Uprev all dependencies

* use ruff instead of flake8 for docs examples linting
2023-01-15 09:57:09 -08:00

31 lines
869 B
Python

from pydantic import BaseModel, Field, PositiveInt
try:
# this won't work since PositiveInt takes precedence over the
# constraints defined in Field meaning they're ignored
class Model(BaseModel):
foo: PositiveInt = Field(..., lt=10)
except ValueError as e:
print(e)
# but you can set the schema attribute directly:
# (Note: here exclusiveMaximum will not be enforce)
class ModelA(BaseModel):
foo: PositiveInt = Field(..., exclusiveMaximum=10)
print(ModelA.model_json_schema())
# if you find yourself needing this, an alternative is to declare
# the constraints in Field (or you could use conint())
# here both constraints will be enforced:
class ModelB(BaseModel):
# Here both constraints will be applied and the schema
# will be generated correctly
foo: int = Field(..., gt=0, lt=10)
print(ModelB.model_json_schema())