In Pydantic, BaseModel
provides .dict()
support, which allows you to easily convert a model instance into a Python dictionary.
This is useful when you need to serialize the data, work with native Python types, or pass data to other libraries (like databases, APIs, etc.).
model_instance.dict(*, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False)
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str
user = User(id=1, name="Abhi", email="abhi@example.com")
print(user.dict())
Output:
{'id': 1, 'name': 'Abhi', 'email': 'abhi@example.com'}
.dict()
is usefulConverts model data to native dict
Makes it easy to:
Return JSON responses
Store in databases
Send over APIs
include
& exclude
user.dict(include={"id", "email"})
# {'id': 1, 'email': 'abhi@example.com'}
user.dict(exclude={"email"})
# {'id': 1, 'name': 'Abhi'}
exclude_unset
Includes only fields explicitly set by the user.
class Product(BaseModel):
name: str
price: float = 99.99
in_stock: bool = True
p = Product(name="Pen")
p.dict()
# {'name': 'Pen', 'price': 99.99, 'in_stock': True}
p.dict(exclude_unset=True)
# {'name': 'Pen'}
exclude_none
Skips fields with None
values.
class Person(BaseModel):
name: str
age: int = None
p = Person(name="John")
p.dict(exclude_none=True)
# {'name': 'John'}
@app.get("/user", response_model=User)
def get_user():
user = User(id=1, name="Abhi", email="abhi@example.com")
return user.dict() # returns as dict which FastAPI converts to JSON
Option | Description |
---|---|
include |
Include only these fields |
exclude |
Exclude specific fields |
exclude_unset |
Exclude fields not explicitly set |
exclude_defaults |
Exclude fields set to their default value |
exclude_none |
Exclude fields that are None |
by_alias |
Use alias names (if any) instead of field names |