Let's say I have a pydantic model with an optional field:
class MyModel(BaseModel):
field_1: str | None
That I instantiate by passing a dict using parse_obj()
Now, I would like the pydantic object to be None if none of the field members were set.
Example:
data_a = {
'field_1': 'value_1'
}
obj_a = MyModel.parse_obj(data_a)
print(type(obj_a)) # <class 'MyModel'>
data_b = {
'foo': 'bar'
}
obj_b = MyModel.parse_obj(data_b)
print(type(obj_b)) # I would like this to be NoneType !
Of course I know I could check if the fields exist in the input data before making any instantiation, but I want to avoid that and make it in a more generic way (imagine like having many different models with different fields).