简体   繁体   中英

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 Any | None but I would like to have it type float | None 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.

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM