11

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!

fallthrough
  • 113
  • 1
  • 1
  • 5
  • 1
    I found a solution. First, give the field a default value `None`. Then, use ```TestModel(id=123).dict(exclude_none=True)``` to exclude it. – fallthrough May 07 '20 at 05:56

4 Answers4

39

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.

SColvin
  • 11,584
  • 6
  • 57
  • 71
7

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}}
enchance
  • 29,075
  • 35
  • 87
  • 127
0

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 }
Djellal Mohamed Aniss
  • 1,723
  • 11
  • 24
  • But everywhere use the validator must have this operate, and it is not related to logical code. Is it possible to complete it in validator?Thanks! – fallthrough May 07 '20 at 03:28
0

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']
DMA2607
  • 29
  • 2