Skip to content
Discussion options

You must be logged in to vote

The key is to use the exclude_unset argument of the .dict method of a Pydantic model:

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}

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@gs11
Comment options

@frankie567
Comment options

@gs11
Comment options

Answer selected by YuriiMotov
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants