Search code examples
pydantic

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

  • 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.