I have a pydantic class like
class MyClass(BaseModel):
base: str
success: bool
date: datetime
I also have a dict like
dict = {
"base": "abc",
"success": True,
"date": "2023-04-30"
}
So I want to do something like obj = MyClass(**dict) but also convert str "date" from dict into datetime "date" of the obj automatically
How to do that in a clean and nice way?
>Solution :
Use a validator to transform the value before it gets assigned to the date field. In the follow code will transform the date into a format supported by Pydantic:
from pydantic import BaseModel, validator
from datetime import datetime
class MyClass(BaseModel):
base: str
success: bool
date: datetime
@validator('date', pre=True)
def validate_date(cls, v):
return f'{v}T00:00'
example = MyClass(**{
"base": "abc",
"success": True,
"date": "2023-04-30"
})
print(example)
Running the above code will output:
base='abc' success=True date=datetime.datetime(2023, 4, 30, 0, 0)