Is there a way of distinguishing between "accepted the default" and "missing" in Pydantic?
Example:
from pydantic import BaseModel
class Test(BaseModel):
c: str | None = None
k1 = Test.model_validate({'c': None})
k2 = Test.model_validate({})
I'd like to be able to distinguish between case k1, where c was explicitly set to the default, compared to k2 where field was not supplied at all.
You can use model_fields_set property to check whether field was passed explicitly or not:
from pydantic import BaseModel
class Test(BaseModel):
c: str | None = None
k1 = Test.model_validate({'c': None})
k2 = Test.model_validate({})
assert "c" in k1.model_fields_set
assert "c" not in k2.model_fields_set