Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PydanticModel().dict(exclude_none=True) from Config class #1696

Closed
jhagege opened this issue Jul 8, 2020 · 2 comments
Closed

PydanticModel().dict(exclude_none=True) from Config class #1696

jhagege opened this issue Jul 8, 2020 · 2 comments

Comments

@jhagege
Copy link

jhagege commented Jul 8, 2020

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 !

@PrettyWood
Copy link
Member

PrettyWood commented Jul 8, 2020

Hello @jhagege!
There is currently no way of doing it directly in the Config. It could maybe be added to #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'}

@jhagege
Copy link
Author

jhagege commented Jul 10, 2020

Great, thanks much !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants