Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete empty field?

Tags:

pydantic

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!

like image 356
fallthrough Avatar asked Mar 19 '26 22:03

fallthrough


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

like image 164
SColvin Avatar answered Mar 21 '26 12:03

SColvin


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}}
like image 32
enchance Avatar answered Mar 21 '26 13:03

enchance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!