Files
pydantic/docs/examples/unenforced_constraints.py
T
Samuel Colvin 7db098fa49 get item type in get_annotation_from_field_info (#909)
* get item type in get_annotation_from_field_info, fix #779

* check constraints are enforced

* add change

* tests for phony constraints

* rewrite get_annotation_from_field_info

* fix tests

* add constaint enforcement to docs

* fix get_annotation_from_field_info coverage

* fix linting

* update docs as per @tiangolo suggestions
2019-10-18 17:41:10 +01:00

27 lines
839 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 Model(BaseModel):
foo: PositiveInt = Field(..., exclusiveMaximum=10)
print(Model.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 Model(BaseModel):
# Here both constraints will be applied and the schema
# will be generated correctly
foo: int = Field(..., gt=0, lt=10)
print(Model.schema())