How to delete empty field?

Viewed 6472

I have a BaseModel like this

from pydantic import BaseModel

class TestModel(BaseModel):
    id: int
    names: str = None

While I validate some data like this

TestModel(id=123).dict() 

I got result

{'id': 123, 'name': None}

But what I expect is:

{'id': 123}

Question: Is there a method to delete empty field? Thanks!

4 Answers

The correct way to do this is with

TestModel(id=123).dict(exclude_none=True)

If you need this everywhere, you can override dict() and change the default.

You can also set it in the model's Config so you don't have to keep writing it down:

class TestModel(BaseModel):
    id: int
    names: str = None

    class Config:
        fields = {'name': {'exclude': True}}

you can perhaps add a root_validator:

@pydantic.root_validator(pre=False)
def check(cls, values):
    if values['some_key'] is None
        del values['some_key']

if you want to delete keys from a dictionary with value "None" :

result = {k: v for k, v in result.items() if v is not None }
Related