Mike Reiche
Mike Reiche

Reputation: 460

Pydantic Field with not zero value

I want to define a field [1] which value must not be zero.

I tried the following: Field(lt=0, gt=0)

ChatGPT recommended Field(ne=0) which does not exists and later suggested to implement and own validator.

@validator("not_zero_field")
def check_not_zero(cls, value):
    if value == 0:
        raise ValueError("Field must not be 0")
    return value

Should ne=0 not be a default feature?

References:

[1] https://docs.pydantic.dev/latest/api/fields/

Upvotes: 0

Views: 580

Answers (1)

Yurii Motov
Yurii Motov

Reputation: 2353

There is no ne=0 feature in pydantic.

And Field(lt=0, gt=0) doesn't work because pydantic checks all the conditions to be true.

The variant with @field_validator works but it will not generate correct JSON-schema.

This code works and generates correct schema:

from typing import TypeAlias, Annotated
from annotated_types import Lt, Gt
from pydantic import BaseModel, ValidationError

negative: TypeAlias = Annotated[int, Lt(0)]
positive: TypeAlias = Annotated[int, Gt(0)]

class A(BaseModel):
    not_zero_field: negative | positive

a = A(not_zero_field=1)
print(a)

a = A(not_zero_field=-1)
print(a)

try:
    a = A(not_zero_field=0)
except ValidationError as e:
    print("Validation error!")

print("Schema:", A.model_json_schema())

Output:

not_zero_field=1
not_zero_field=-1
Validation error!
Schema: {'properties': {'not_zero_field': {'anyOf': [{'exclusiveMaximum': 0, 'type': 'integer'}, {'exclusiveMinimum': 0, 'type': 'integer'}], 'title': 'Not Zero Field'}}, 'required': ['not_zero_field'], 'title': 'A', 'type': 'object'}

Upvotes: 1

Related Questions