Pydantic transform field

Pydantic Transform Field

Pydantic is a library in Python used for data validation and parsing. Pydantic provides a powerful feature called “Transform Field” that allows you to transform the input data before validation. This can be particularly useful when you need to convert the incoming values to a different format or perform some manipulation on them.

To use the transform field feature, you can define a method in your Pydantic model class with the name “_[field_name]“. This method will be automatically called before the validation of the respective field. Inside this method, you can define the transformation logic.

Here’s an example to illustrate the usage of the transform field feature:


from pydantic import BaseModel

class User(BaseModel):
    name: str

    def _name(self, value):
        # Capitalize the name before validation
        return value.capitalize()

# Creating an instance of the User model
user = User(name="john doe")

# Accessing the transformed name
print(user.name)  # Output: "John doe"

    

In the above example, the “_name” method is defined and it capitalizes the name before validation. So, even if the input is in lowercase, it will be transformed to capitalize the first letter.

The transform field feature can be very handy when you need to preprocess the incoming data to fit your requirements or perform any necessary data manipulation before validation.

Leave a comment