fallthrough
fallthrough

Reputation: 113

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!

Upvotes: 11

Views: 22578

Answers (5)

Michael
Michael

Reputation: 156

just gonna leave this here. use model_validator decorator with mode=after. delete the attribute if its value is none. for pydantic ver 2.x

from pydantic import BaseModel, model_validator
from rich import print
from typing import print


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

    @model_validator(mode="after")
    @classmethod
    def remove_null(cls, data: "TestModel"):
        if data.names is None:
            del data.names

if __name__ == "__main__":
    print(TestModel(id=1, names="Jane John Doe"))
    print(TestModel(id=1, names=None))
    print(TestModel(id=1))

You just gotta be careful when accessing the attribute names.

Upvotes: 0

enchance
enchance

Reputation: 30431

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}}

Upvotes: 10

DMA2607
DMA2607

Reputation: 39

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

Upvotes: 1

Samuel Colvin
Samuel Colvin

Reputation: 13289

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.

Upvotes: 41

Djellal Mohamed Aniss
Djellal Mohamed Aniss

Reputation: 1733

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 }

Upvotes: 0

Related Questions