Pydantic: PydanticModel().dict(exclude_none=True) from Config class

Created on 8 Jul 2020  路  2Comments  路  Source: samuelcolvin/pydantic

Hi, is it possible to use a parameter to specify to automatically use the option "exclude_none=True" from the Config class of a Pydantic model ?

I'd like to encapsulate this logic and not require from users of the model to know about this option.

Thanks !

feature request

Most helpful comment

Hello @jhagege!
There is currently no way of doing it directly in the Config. It could maybe be added to https://github.com/samuelcolvin/pydantic/issues/660.
In the meantime I reckon you can just override the default value in your own BaseModel:

from pydantic import BaseModel as PydanticBaseModel

class BaseModel(PydanticBaseModel):
    def dict(self, exclude_none=True, **kwargs):
        return super().dict(exclude_none=exclude_none, **kwargs)
class M(BaseModel):
    a: str = None
    b: str

m = M(b='a')
assert m.dict() == {'b': 'a'}
assert m.dict(exclude_none=False) == {'a': None, 'b': 'a'}

All 2 comments

Hello @jhagege!
There is currently no way of doing it directly in the Config. It could maybe be added to https://github.com/samuelcolvin/pydantic/issues/660.
In the meantime I reckon you can just override the default value in your own BaseModel:

from pydantic import BaseModel as PydanticBaseModel

class BaseModel(PydanticBaseModel):
    def dict(self, exclude_none=True, **kwargs):
        return super().dict(exclude_none=exclude_none, **kwargs)
class M(BaseModel):
    a: str = None
    b: str

m = M(b='a')
assert m.dict() == {'b': 'a'}
assert m.dict(exclude_none=False) == {'a': None, 'b': 'a'}

Great, thanks much !

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jasonkuhrt picture jasonkuhrt  路  21Comments

MrMrRobat picture MrMrRobat  路  22Comments

maxrothman picture maxrothman  路  26Comments

demospace picture demospace  路  26Comments

sm-Fifteen picture sm-Fifteen  路  45Comments