Search code examples
pythonpydantictyping

How to get Decimal | None field type in pydantic with condecimal?


I am creating a model where the field is constrained by decimal places and is positive. I could just create a custom validator, but I was hoping to have condecimal work.

class Example(BaseModel):
  some_field: Optional[condecimal(ge=0.01, decimal_places=2)] = Field(alias="Some alias")

some_field is type Any | None but I would like to have it type float | None

I have also tried doing

some_field: Optional[float] = Field(alias="Some alias", ge=0.01, decimal_places=2)

but this gives ValueError: On field "some_field" the following field constraints are set but not enforced: decimal_places.


Solution

  • You get the error for second version because float and decimal are different types (see here). A float cannot be constrained to the decimal places, but a decimal can.

    You can fix it like this:

    from typing import Optional
    from pydantic import BaseModel, Field
    from decimal import Decimal
    
    
    class Example(BaseModel):
      some_field: Optional[Decimal] = Field(ge=0.01, decimal_places=2)
    
    
    Example(some_field=0.11)
    >>> Example(some_field=Decimal('0.11'))