Building Data Models with Pydantic
Pydantic is a powerful Python library for data validation and settings management using Python type annotations. This challenge will test your ability to define and utilize Pydantic models to enforce data structure and type safety in your applications. You'll be creating models to represent different data structures, including nested models and lists, and validating data against these models.
Problem Description
You are tasked with creating Pydantic models to represent various data structures. These models should define the expected data types and constraints for each field. The goal is to ensure that incoming data conforms to a specific schema, preventing errors and improving code reliability. You will need to define models for a User (with nested Address), an Order (containing a list of OrderItem), and a Product. Each model should include appropriate data types, validation rules (e.g., minimum lengths, allowed values), and default values where applicable.
Key Requirements:
- User Model: Represents a user with fields for
id(integer),username(string, minimum length 3),email(string, email format validation),age(integer, minimum 18), and a nestedAddressmodel. - Address Model: Represents a user's address with fields for
street(string),city(string),state(string, length 2), andzip_code(string, length 5). - OrderItem Model: Represents an item in an order with fields for
product_id(integer),quantity(integer, minimum 1), andprice(float, minimum 0.01). - Order Model: Represents an order with fields for
order_id(integer),user_id(integer),order_date(string, ISO 8601 format), and a list ofOrderItemmodels. - Product Model: Represents a product with fields for
product_id(integer),name(string, minimum length 1),description(string), andprice(float, minimum 0.0).
Expected Behavior:
- The models should be defined using Pydantic's class-based syntax.
- Data validation should be performed automatically when creating instances of the models.
- Invalid data should raise appropriate Pydantic validation errors.
- Default values should be applied when fields are not provided during model instantiation.
Examples
Example 1:
Input:
user_data = {
"username": "john",
"email": "john@example.com",
"age": 25,
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip_code": "91234"
}
}
Output:
A valid User model instance.
Explanation:
The input data matches the expected schema for the User model. All fields are present and of the correct type.
Example 2:
Input:
order_data = {
"order_id": 1,
"user_id": 123,
"order_date": "2023-10-27",
"items": [
{"product_id": 1, "quantity": 2, "price": 10.0},
{"product_id": 2, "quantity": 1, "price": 25.50}
]
}
Output:
A valid Order model instance.
Explanation:
The input data conforms to the Order model's schema, including the list of OrderItem dictionaries.
Example 3: (Edge Case - Invalid Email)
Input:
user_data = {
"username": "jane",
"email": "invalid-email",
"age": 30,
"address": {
"street": "456 Oak Ave",
"city": "Springfield",
"state": "IL",
"zip_code": "62704"
}
}
Output:
ValidationError: 1 validation error for User
email
field required (error_code: "field-required")
Explanation:
The email address is invalid and does not match the expected email format. Pydantic raises a ValidationError.
Constraints
- All string fields must be validated for type and length where specified.
- Integer fields must be validated for type and minimum values where specified.
- Float fields must be validated for type and minimum values where specified.
- The
order_datefield must be a string in ISO 8601 format (YYYY-MM-DD). - The
emailfield must be a valid email address. - The
statefield in theAddressmodel must be exactly 2 characters long. - The
zip_codefield in theAddressmodel must be exactly 5 characters long. - The
quantityfield in theOrderItemmodel must be at least 1. - The
pricefields inOrderItemandProductmodels must be at least 0.01 and 0.0 respectively.
Notes
- Consider using Pydantic's built-in validation features, such as
validatormethods and type annotations. - Think about how to handle missing fields and provide default values where appropriate.
- Pay close attention to the data types and constraints specified for each field.
- Test your models with both valid and invalid data to ensure they are working correctly.
- You don't need to implement any data persistence or external API calls; focus solely on defining and validating the Pydantic models.