Can I make a default model in Pydantic if None is passed in the field?
I am new to pydantic and searched for relevant answers but could not find any. I have the following code,
from typing import Optional,List
from pydantic import BaseModel
class FieldInfo(BaseModel):
value: Optional[str] = ""
confidence: Optional[float] = -1.0
class UserInfo(BaseModel):
first_name: Optional[FieldInfo]
last_name: Optional[FieldInfo]
user_info = {"user":{"first_name":["john",0.98], "last_name":["doe",0.98]}}
user = UserInfo(**{k:{"value":v[0],"confidence":v[1]} for k,v in user_info["user"].items()})
print(user)
gives me
first_name=FieldInfo(value='john', confidence=0.98) last_name=FieldInfo(value='doe', confidence=0.98)
but if last_name is None i.e.
user_info = {"user":{"first_name":["john",0.98]}}
user = UserInfo(**{k:{"value":v[0],"confidence":v[1]} for k,v in user_info["user"].items()})
print(user)
I get
first_name=FieldInfo(value='john', confidence=0.98) last_name=None
How can i get it take the default value if there is no values is passed, like below
first_name=FieldInfo(value='john', confidence=0.98) last_name=FieldInfo(value='', confidence=-1.0)
source https://stackoverflow.com/questions/74185763/how-to-set-the-default-model-to-a-variable-if-none-was-passed
Comments
Post a Comment