Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Using Fields

00:00 Using Fields for Customization and Metadata So far, your employee model validates the data type of each field and ensures some of the fields such as email, date of birth, and department take on valid formats.

00:14 But let’s say you want to ensure that salary is a positive number, name isn’t an empty string, and email contains your company’s domain name.

00:22 You can use Pydantic’s Field class to accomplish this. The Field class allows you to customize and add metadata to your model’s fields.

00:31 Let’s take a look at an example. This file is based on the previous example, so save a copy under a new name and make the modifications to the copy as this will make comparisons easier.

00:43 The imports need to be updated first, adding ConfigDict, which will be used later on and Field as this will be used for a number of the definitions.

00:54 Next, the class model _config is set with a ConfigDict object. This allows control of Pydantic’s behavior. Here populate_by_name is set to True, which will make the validation of alias fields that you’ll see later on work in a more intuitive manner.

01:12 The full range of configuration settings can be seen in the Pydantic documentation at the link seen on screen.

01:21 Next, you add Field with appropriate parameters to add additional metadata and validation to the fields. default_factory: you use this to define a callable that generates default values.

01:34 Here you set default_factory to uuid4. This calls uuid4 to generate a random UUID for employee_ID when needed.

01:45 You can also use a lambda function for more flexibility. frozen: this is a Boolean parameter you can set to make your fields immutable. So when frozen is set to True, the corresponding field can’t be changed after the model is instantiated.

02:01 In this example, employee_ID, name, and date_of_birth will all be made immutable using the frozen parameter.

02:11 min_length: You can control the length of string fields with min_length and max_length. Here you ensure that name is at least one character long.

02:26 pattern: for string fields, you can set pattern to a regex expression to match whatever pattern you are expecting for that field.

02:35 Here, when you use this regex expression for email, Pydantic will ensure that every email ends with @example.com. alias: you can use this parameter when you want to assign an alias for your fields.

02:51 You can allow date_of_birth to be called birthdate or salary to be called compensation. You can use these aliases when instantiating or serializing a model. repr: this Boolean parameter determines whether a field is displayed in the model’s field representation. Here, you won’t see date_of_birth or salary when you print an employee instance.

03:22 gt: this parameter, short for greater than, is used for numeric fields to set minimum values. Here, setting gt=0, ensures salary is always a positive number.

03:34 Pydantic also has other number constraints such as lt, which is short for less than.

03:43 To see this in action, try creating an employee model with incorrect data. First, you import your updated employee model and then you attempt to validate a dictionary with incorrect data.

04:17 Pydantic responds with three validation errors saying the name needs to be at least one character, email should match the company’s domain and salary should be greater than zero.

04:28 Now take a look at the additional features you get when you validate correct employee data.

04:36 Here, a dictionary will be created using birthdate instead of date_of_birth and compensation instead of salary.

04:43 Pydantic will recognize these aliases and assign the values to the correct field names internally. You then create the Employee model with the model_validate() method.

04:59 Because you set repr to False, you can see that salary and date_of_birth aren’t displayed in the employee representation.

05:07 You have to explicitly access them as attributes to see their values.

05:15 You can change the value of department from IT to HR.

05:21 This is acceptable because department isn’t a frozen field, but when you try to change name,

05:30 Pydantic gives you an error saying that name is a frozen field. You now have a solid grasp of Pydantic’s base model and field classes. With these alone, you can define many different validation rules and metadata on your data schemas, but sometimes this isn’t enough.

05:48 So next you’ll take your field validation even further with Pydantic validators.

Become a Member to join the conversation.