Python

How to Simplify Complex Data Models with Pydantic Alias

Making complicated data models easier is simple with Pydantic aliases. Pydantic is like a helper tool in Python that checks the data and settings. It’s really useful when dealing with tricky data models. Using Pydantic aliases is like giving a nickname to different parts of our data. It’s like when we have a long name, people use a shorter version because it’s easier to say. With Pydantic aliases, we can simplify the complicated data models without losing the important original names that are used to keep the data organized.

Method 1: Simplification of Complex Data Models with Pydantic Alias

To explore how we can use the Pydantic aliases to simplify the complex data model, imagine that we are building an online shopping platform. Each thing we sell, like a cosmetics or jewelry product, has its special details like name, how much it costs, what it’s like, and whether it’s ready to buy. To keep all these details organized, we start by creating something like a data structure called “Product”. Inside this data structure, we define the fields or say we put the labels such as “product_name”, “product_price”, “product_description”, and “product_availability” as given in the following:

class Product:
    def __init__(self, product_name, product_price, product_description, product_availability):
        self.product_name = product_name
        self.product_price = product_price
        self.product_description = product_description
        self.product_availability = product_availability

Suppose that our business is successful and our shop gets bigger. Handling all these details can get a bit messy. This is where Pydantic aliases come to help. Instead of using the long and sometimes tricky names that we create, we can give them simpler and more friendly names with Pydantic aliases. This can be understood as the names that we describe in the “Products” class since its required fields for the products’ detailed information were too long or maybe complex. So, we now give them all a nickname, e.g. we can replace the “product_name” attribute as just “name”.

This can be done using the Pydantic “Field aliases”. We import the Pydantic’s “BaseModel” and the “Field” first. Then, we create a model name again as “product” that will inherit from the “BaseModel”. Then, in this model, we use the “Field” (alias = “original name”) method as shown in the following lines of code:

from pydantic import BaseModel, Field

Each attribute in the “Product” class is replaced with the assistance of the “Field” class. With the “alias” parameter, we assign the alternative, more reader-friendly labels to the original attributes. Here, we get the benefits of Pydantic into our work. We design a special “Product” class model to use the “field” alias to change the names of the attributes in the data as mentioned previously in the “product” structure. Each detail of the product gets a new name which is easier to understand. This is how the aliases work. They give us a way to change the names to something shorter and simpler.

class Product(BaseModel):
    name: str = Field(alias="product_name")
    price: float = Field(alias="product_price")
    description: str = Field(alias="product_description")
    availability: bool = Field(alias="product_availability")

After we set up these special names with the help of the aliases in the data model, let’s see how we can use them to create things and work with the details. In this step, we list the details for a new thing that we want to sell. Then, we create this thing using the new names we made. We can use these new, easier names when we want to see what the thing is called or how much it costs. It’s like having a special name tag for each detail.

product_data = {
    "product_name": "skin serum",
    "product_price": 100,
    "product_description": "Serum for the rehydration of the skin.",
    "product_availability": True
}

product_instance = Product(**product_data)

By carefully following these steps, we will learn how to use the Pydantic aliases to simplify the complex things. We make our work easier to read and understand using names that make more sense. And even though we change the names, our computer still knows the original names it needs to do all the important work behind this.

!pip install pydantic
class Product:
    def __init__(self, product_name, product_price, product_description, product_availability):
        self.product_name = product_name
        self.product_price = product_price
        self.product_description = product_description
        self.product_availability = product_availability
from pydantic import BaseModel, Field
class Product(BaseModel):
    name: str = Field(alias="product_name")
    price: float = Field(alias="product_price")
    description: str = Field(alias="product_description")
    availability: bool = Field(alias="product_availability")
product_data = {
    "product_name": "skin serum",
    "product_price": 100,
    "product_description": "Serum for the rehydration of the skin.",
    "product_availability": True
}

products= Product(**product_data)

print(products.name)
print(products.price)

Method 2: Organizing Information with Pydantic Alias

Imagine we are creating a data organizer application where we want to keep track of adorable plants in our neighborhood. Each plant comes with various details like its name, age, breed, and owner’s contact. At the beginning, our system might have labels such as “plant_name”, “plant_age”, “plant_breed”, and “plant_owner”.

We begin by creating the Original Plant Information Model to define and name the required attributes for this application. We can start by building the system like this:

class Plant:
    def __init__(self, plant_name, plant_age, plant_breed, plant_owner):
        self.plant_name = plant_name
        self.plant_age = plant_age
        self.plant_breed = plant_breed
        self.plant_owner= plant_owner

The next task is to bring in the Pydantic “Field” alias since, as more plants join the registry, handling these long names becomes a difficult task. That’s where Pydantic aliases come to save us. Instead of dealing with these complex names, we can give them friendly, shorter names that are easier to understand.

from pydantic import BaseModel, Field
class PlantRecord(BaseModel):
    name: str = Field(alias="plant_name")
    age: int = Field(alias="plant_age")
    breed: str = Field(alias="plant_breed")
    owner_contact: str = Field(alias="plant_owner")

We introduce the Pydantic “field” alias to make our life easier. We create the “PlantRecord” class by borrowing Pydantic’s tricks. Using the “Field” class, we create names for each detail. These new names are like nicknames which make our code neater and simpler.

With our fancy new names in place, let’s see how this works with plant information. In this step, we gather all the plant stuff in a group and call it “plantdata”. We make a special instance of the “PlantRecord” class using this. We use the new names that we created to know the plant’s details. It’s like having tiny flags/tags for each detail that show what information is for what plant.

plant_data = {
    "plant_name": "lavender",
    "plant_age": 2,
    "plant_breed": "fragrantplant",
    "plant_owner": "Andrew"
}

plant_instance = PlantRecord(**plant_data)

We successfully implemented these steps and transformed the complicated plant data into simple data. Pydantic aliases are like small nametags which make our code easier to read. While we replace the names, our computer still knows the original ones that are needed for important tasks.

!pip install pydantic
class Plant:
    def __init__(self, plant_name, plant_age, plant_breed, plant_owner):
        self.plant_name = plant_name
        self.plant_age = plant_age
        self.plant_breed = plant_breed
        self.plant_owner= plant_owner
from pydantic import BaseModel, Field
class PlantRecord(BaseModel):
    name: str = Field(alias="plant_name")
    age: int = Field(alias="plant_age")
    breed: str = Field(alias="plant_breed")
    owner_contact: str = Field(alias="plant_owner")
plant_data = {
    "plant_name": "lavender",
    "plant_age": 2,
    "plant_breed": "fragrantplant",
    "plant_owner": "Andrew"
}

plant_instance = PlantRecord(**plant_data)

print(plant_instance.name)  
print(plant_instance.age)

Complex data models become smooth and easier to deal with Pydantic aliases. They are our secret hacks to remove complexity and create understandable code. With Pydantic, we have taken a big step towards tidier, more manageable software that’s ready to grow.

Conclusion

Pydantic aliases are a powerful tool to simplify the complex data models by offering the reader-friendly field names. These aliases allow the developers to enhance the code readability, reduce complexity, and include the data management without compromising the original functionality. By utilizing Pydantic’s capability to assign aliases to fields, the developers can maintain a clear and organized codebase, making it easier to collaborate, maintain, and expand the applications.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.