0

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/

1 Answer 1

1

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'}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.