iTranslated by AI
Field Constraints in Pydantic V2
Pydantic V2 now issues a warning when unsupported keywords are used in Field(). This article explains how to set range constraints for integers.
Background
In Pydantic V1, no warning was issued even if minimum and maximum were specified as keyword arguments.
class Score(BaseModel):
score: int = Field(minimum=0, maximum=20)
However, running this code in Pydantic V2 displays the following warning:
PydanticDeprecatedSince20: Using extra keyword arguments on `Field` is deprecated
and will be removed. Use `json_schema_extra` instead. (Extra keys: 'minimum', 'maximum').
While the warning suggests using json_schema_extra, you should actually use the official constraint parameters of Pydantic V2.
ge/le Constraint Parameters
In Pydantic V2, specifying ge (greater than or equal) and le (less than or equal) will result in them being converted to minimum and maximum in the JSON Schema.
Constraint Description JSON Schema leThe value must be less than or equal to this number maximumkeywordgeThe value must be greater than or equal to this number minimumkeyword
import json
from pydantic import BaseModel, Field
class Score(BaseModel):
score: int = Field(ge=0, le=20)
print(json.dumps(Score.model_json_schema(), indent=2))
{
"properties": {
"score": {
"maximum": 20,
"minimum": 0,
"title": "Score",
"type": "integer"
}
},
"required": [
"score"
],
"title": "Score",
"type": "object"
}
In this way, specifying ge=0, le=20 automatically sets "minimum": 0 and "maximum": 20 in the JSON schema.
-
ge=0:score >= 0(0 or more) -
le=20:score <= 20(20 or less)
Verification of Validation Behavior
# Valid values
valid = Score(score=15) # OK
# Values out of range are rejected
invalid_low = Score(score=-1) # ValidationError
invalid_high = Score(score=21) # ValidationError
# Boundary values are allowed
edge_low = Score(score=0) # OK
edge_high = Score(score=20) # OK
json_schema_extra (Deprecated)
class Score(BaseModel):
score: int = Field(json_schema_extra={"minimum": 0, "maximum": 20})
While the result is the same if you are only outputting the JSON schema, validation (numeric range checking) will not function because these keywords are not officially recognized by Pydantic.
Summary
- Use
geandlefor integer range constraints. - Use
json_schema_extraonly when adding custom metadata that cannot be represented by standard constraint parameters.
References
Discussion