Enum field validation fallback #2468
Answered
by
PrettyWood
dwbelliston
asked this question in
Question
-
Hey! What is the approach to provide a default value if a field validation fails? Example:
If an existing record has a value outside this enum, id like to set it to a default on the enum. Is this possible? |
Beta Was this translation helpful? Give feedback.
Answered by
PrettyWood
Mar 4, 2021
Replies: 1 comment 1 reply
-
Hi @dwbelliston from enum import Enum, auto
from pydantic import BaseModel
class Fruit(Enum):
APPLE = auto()
PEAR = auto()
@classmethod
def _missing_(cls, value):
return cls.APPLE
class Model(BaseModel):
fruit: Fruit
print(Model(fruit=Fruit.APPLE).fruit) # Fruit.APPLE
print(Model(fruit=Fruit.PEAR).fruit) # Fruit.PEAR
print(Model(fruit='invalid').fruit) # Fruit.APPLE Hope it helps! |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
dwbelliston
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @dwbelliston
IMO the best way is to overwrite
_missing_
in yourEnum
like thisHope it helps!