'How to delete empty field?

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!



Solution 1:[1]

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']

Solution 2:[2]

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 }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DMA2607
Solution 2 Djellal Mohamed Aniss