5

So I have the following line of code:

item: Optional[int] = Field(None, ge=1, le=168)

and I would like to have possibility to set -1 value as well. So, I need to exclude zero values, but I would like to allow a -1 value and values from 1 to 168.

Is there any way to do this?

Chris
  • 18,724
  • 6
  • 46
  • 80
SimonZen
  • 131
  • 1
  • 11
  • I am not sure if I understand your question corrently but `ge` means `greater or equals to` and `le` means `less than or equals to`. So if you want a custom range, you need to change these params accordingly. For example `Field(None, ge=-1, le=168)` – Bijay Regmi Jul 27 '22 at 11:27
  • 1
    it so than I need to exclude zero value so it will look like '''-1''' and from 1 to 168 – SimonZen Jul 27 '22 at 11:32
  • 1
    You could extend the range down to -1, and then add a custom Pydantic validator checking that it is not 0? – M.O. Jul 27 '22 at 12:04
  • yeap, I thought about it, but hope that there is prettier solution for this problem – SimonZen Jul 27 '22 at 13:13

1 Answers1

6

You could specify the range from -1 to 168 and also have a custom Pydantic validator to check whether or not the value is equal to 0. If so, raise ValueError. If the Pydantic model was instead used to define query parameters for the endpoint (using Depends()), please have a look at this answer.

Example

from fastapi import FastAPI
from typing import Optional
from pydantic import Field, BaseModel, validator

app = FastAPI()

class Foo(BaseModel):
    item: Optional[int] = Field(None, ge=-1, le=168)

    @validator('item')
    def prevent_zero(cls, v):
        if v == 0: 
            raise ValueError('ensure this value is not 0')
        return v
 
@app.post("/")
def submit(foo: Foo):
    return foo
Chris
  • 18,724
  • 6
  • 46
  • 80