Is there any in-built way in pydantic to specify options? For example, let's say I want a string value that must either have the value "foo" or "bar".
I know I can use regex validation to do this, but since I use pydantic with FastAPI, the users will only see the required input as a string, but when they enter something, it will give a validation error. All in-built validations of pydantic are displayed in the api interface, so would be great if there was something like
class Input(BaseModel):
option: "foo" || "bar"
Pydantic models can be defined with a custom root type by declaring the __root__ field. The root type can be any type supported by pydantic, and is specified by the type hint on the __root__ field.
constr is a specific type that give validation rules regarding this specific type. You have equivalent for all classic python types.
Pydantic is a useful library for data parsing and validation. It coerces input types to the declared type (using type hints), accumulates all the errors using ValidationError & it's also well documented making it easily discoverable.
See also MongoDB Field Names. While in Pydantic, the underscore prefix of a field name would be treated as a private attribute. The alias is defined so that the _id field can be referenced.
Yes, you can either use an enum:
class Choices(Enum):
foo = 'foo'
bar = 'bar'
class Input(BaseModel):
option: Choices
see here
Or you can use Literal
:
class Input(BaseModel):
option: Literal['foo', 'bar']
see here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With