How can I differentiate explicit nulls when creating the request model? #3107
-
|
For updating data in a system, a PATCH operation accepts partial payloads to only update the explicitly included properties. How can I configure the model so that the parsed instance represents both absent and explicit nulls? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
|
The key is to use the
Here is a simple example: from typing import Optional
from pydantic import BaseModel
class Model(BaseModel):
my_field: Optional[int] = None
m1 = Model()
assert m1.dict(exclude_unset=True) == {}
m2 = Model(my_field=None)
assert m2.dict(exclude_unset=True) == {"my_field": None} |
Beta Was this translation helpful? Give feedback.
The key is to use the
exclude_unsetargument of the.dictmethod of a Pydantic model:Here is a simple example: