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!
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.
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With