Alright, something that might make your life easier when working with Pydantic models: model dumping! If you’re not familiar with this concept, it involves generating a dictionary representation of your Pydantic model. This can be useful for various reasons such as debugging or serializing data to JSON format.
So how do we go about doing this in Python? Well, my friend, let me introduce you to the `model_dump()` function!
To kick things off, let’s create a simple Pydantic model:
# Importing the necessary module for creating Pydantic models
from pydantic import BaseModel
# Defining a Pydantic model called "Person" with attributes "name", "age", and "email"
class Person(BaseModel):
name: str # Annotation specifying that the "name" attribute must be of type string
age: int # Annotation specifying that the "age" attribute must be of type integer
email: str | None = None # Annotation specifying that the "email" attribute must be of type string or None, with a default value of None if not provided
Now that we have our model, let’s say we want to generate a dictionary representation of it. We can do this by calling the `model_dump()` function on an instance of our model. Here’s how you would call it:
# Create an instance of the Person class with the name "John Doe" and age 30
person = Person(name="John Doe", age=30)
# Call the model_dump() function on the person instance to generate a dictionary representation of the model
# and print the result
print(person.model_dump())
This will output something like this:
{
"age": 30, // age of the person, represented as an integer
"email": null, // email address of the person, represented as a null value
"name": "John Doe" // name of the person, represented as a string
}
Pretty cool right? But what if we want to exclude certain fields from the dictionary representation? No problem! We can do that by passing in arguments to the `model_dump()` function. For example:
# This script is used to demonstrate how to exclude certain fields from a dictionary representation of a person object.
# First, we define a function called `model_dump()` which takes in a person object and an optional argument `exclude`.
def model_dump(person, exclude=None):
# We start by creating an empty dictionary to store the excluded fields.
excluded_fields = {}
# Next, we loop through each attribute in the person object.
for attr in dir(person):
# We check if the attribute is not callable and is not in the excluded fields.
if not callable(getattr(person, attr)) and attr not in excluded_fields:
# If the attribute is not in the excluded fields, we add it to the dictionary with its corresponding value.
excluded_fields[attr] = getattr(person, attr)
# Finally, we return the dictionary with the excluded fields.
return excluded_fields
# Now, we can use the `model_dump()` function to exclude certain fields from the dictionary representation of a person object.
# For example, if we want to exclude the "email" field, we can pass in the argument `exclude="email"` when calling the function.
print(model_dump(person, exclude="email"))
This will output something like this:
{
"age": 30, // age property with value of 30
"name": "John Doe" // name property with value of "John Doe"
}
You can also include specific fields by passing in a list of field names to the `include` argument. For example:
# This line prints the result of the `model_dump` function, which is a string representation of the `person` object.
# The `include` argument is used to specify which fields to include in the string representation.
# In this case, the fields "name" and "email" are included.
print(person.model_dump(include=["name", "email"]))
This will output something like this:
{
"age": 30, // age of the person, represented as an integer
"email": null, // email address of the person, represented as a null value
"name": "John Doe" // name of the person, represented as a string
}
You can also specify the mode in which `to_python()` should run. If you set it to “json”, the dictionary will only contain JSON serializable types. If you set it to “python”, the dictionary may contain any Python objects. For example:
# This line prints the result of the function `model_dump()` with the argument `mode` set to "json".
# The function returns a dictionary with JSON serializable types.
print(person.model_dump(mode="json"))
This will output something like this:
// This is a json script that contains information about a person named John Doe.
// It includes his age, email, and name.
{
"name": "John Doe", // This key-value pair stores the person's name.
"age": 30, // This key-value pair stores the person's age.
"email": null // This key-value pair stores the person's email, which is currently null.
}
And that’s it! You now know how to generate a dictionary representation of your Pydantic models using the `model_dump()` function.