0
# Core Models and Validation
1
2
Base model classes, field definitions, and core validation functionality that forms the foundation of pydantic's data validation capabilities.
3
4
## Capabilities
5
6
### BaseModel
7
8
The primary base class for creating pydantic models with comprehensive validation, serialization, and schema generation capabilities.
9
10
```python { .api }
11
class BaseModel(metaclass=ModelMetaclass):
12
"""
13
Base class for creating pydantic models.
14
15
Provides validation, serialization, and schema generation functionality.
16
"""
17
18
def __init__(self, **data):
19
"""
20
Initialize model with validation.
21
22
Args:
23
**data: Field values as keyword arguments
24
25
Raises:
26
ValidationError: If validation fails
27
"""
28
29
@classmethod
30
def model_validate(cls, obj, /, *, strict=None, from_attributes=None, context=None):
31
"""
32
Validate data and create model instance.
33
34
Args:
35
obj: Data to validate (dict, model instance, etc.)
36
strict (bool, optional): Enable strict validation mode
37
from_attributes (bool, optional): Extract data from object attributes
38
context (dict, optional): Additional context for validation
39
40
Returns:
41
Instance of the model
42
43
Raises:
44
ValidationError: If validation fails
45
"""
46
47
@classmethod
48
def model_validate_json(cls, json_data, /, *, strict=None, context=None):
49
"""
50
Validate JSON string and create model instance.
51
52
Args:
53
json_data (str | bytes): JSON string to validate
54
strict (bool, optional): Enable strict validation mode
55
context (dict, optional): Additional context for validation
56
57
Returns:
58
Instance of the model
59
60
Raises:
61
ValidationError: If validation fails
62
"""
63
64
@classmethod
65
def model_validate_strings(cls, obj, /, *, strict=None, context=None):
66
"""
67
Validate data with string inputs and create model instance.
68
69
Args:
70
obj: Data to validate
71
strict (bool, optional): Enable strict validation mode
72
context (dict, optional): Additional context for validation
73
74
Returns:
75
Instance of the model
76
77
Raises:
78
ValidationError: If validation fails
79
"""
80
81
def model_dump(self, *, include=None, exclude=None, context=None, by_alias=False,
82
exclude_unset=False, exclude_defaults=False, exclude_none=False,
83
round_trip=False, warnings=True, serialize_as_any=False):
84
"""
85
Convert model to dictionary.
86
87
Args:
88
include: Fields to include
89
exclude: Fields to exclude
90
context (dict, optional): Serialization context
91
by_alias (bool): Use field aliases in output
92
exclude_unset (bool): Exclude fields that weren't set
93
exclude_defaults (bool): Exclude fields with default values
94
exclude_none (bool): Exclude fields with None values
95
round_trip (bool): Enable round-trip serialization
96
warnings (bool): Show serialization warnings
97
serialize_as_any (bool): Serialize using Any serializer
98
99
Returns:
100
dict: Model data as dictionary
101
"""
102
103
def model_dump_json(self, *, include=None, exclude=None, context=None, by_alias=False,
104
exclude_unset=False, exclude_defaults=False, exclude_none=False,
105
round_trip=False, warnings=True, serialize_as_any=False):
106
"""
107
Convert model to JSON string.
108
109
Args:
110
include: Fields to include
111
exclude: Fields to exclude
112
context (dict, optional): Serialization context
113
by_alias (bool): Use field aliases in output
114
exclude_unset (bool): Exclude fields that weren't set
115
exclude_defaults (bool): Exclude fields with default values
116
exclude_none (bool): Exclude fields with None values
117
round_trip (bool): Enable round-trip serialization
118
warnings (bool): Show serialization warnings
119
serialize_as_any (bool): Serialize using Any serializer
120
121
Returns:
122
str: Model data as JSON string
123
"""
124
125
def model_copy(self, *, update=None, deep=False):
126
"""
127
Create a copy of the model.
128
129
Args:
130
update (dict, optional): Fields to update in the copy
131
deep (bool): Create deep copy
132
133
Returns:
134
New instance of the model
135
"""
136
137
@classmethod
138
def model_construct(cls, _fields_set=None, **values):
139
"""
140
Create model instance without validation.
141
142
Args:
143
_fields_set (set, optional): Set of field names that were explicitly set
144
**values: Field values
145
146
Returns:
147
Instance of the model
148
"""
149
150
@classmethod
151
def model_json_schema(cls, by_alias=True, ref_template='#/$defs/{model}'):
152
"""
153
Generate JSON schema for the model.
154
155
Args:
156
by_alias (bool): Use field aliases in schema
157
ref_template (str): Template for schema references
158
159
Returns:
160
dict: JSON schema
161
"""
162
163
@classmethod
164
def model_rebuild(cls, *, force=False, raise_errors=True, _parent_namespace_depth=2,
165
_types_namespace=None):
166
"""
167
Rebuild model schema and validators.
168
169
Args:
170
force (bool): Force rebuild even if not needed
171
raise_errors (bool): Raise errors during rebuild
172
_parent_namespace_depth (int): Depth for namespace resolution
173
_types_namespace (dict, optional): Types namespace
174
"""
175
176
@property
177
def model_extra(self):
178
"""dict: Extra fields not defined in the model"""
179
180
@property
181
def model_fields_set(self):
182
"""set: Set of field names that were set during initialization"""
183
184
@classmethod
185
@property
186
def model_fields(cls):
187
"""dict: Dictionary of field name to FieldInfo"""
188
189
@classmethod
190
@property
191
def model_computed_fields(cls):
192
"""dict: Dictionary of computed field name to ComputedFieldInfo"""
193
```
194
195
### RootModel
196
197
Generic base class for models where the entire model is a single value, useful for wrapping primitive types or creating type aliases with validation.
198
199
```python { .api }
200
class RootModel(BaseModel, Generic[RootType]):
201
"""
202
Base class for models where the root value is the entire model.
203
204
Useful for creating validated type aliases or wrapping primitive types.
205
"""
206
207
root: RootType
208
209
def __init__(self, root: RootType = PydanticUndefined, **data):
210
"""
211
Initialize with root value.
212
213
Args:
214
root: The root value for the model
215
**data: Additional data (typically empty for RootModel)
216
"""
217
218
@classmethod
219
def model_construct(cls, root, _fields_set=None):
220
"""
221
Create RootModel instance without validation.
222
223
Args:
224
root: Root value
225
_fields_set (set, optional): Set of fields that were set
226
227
Returns:
228
RootModel instance
229
"""
230
```
231
232
### Field Function
233
234
Create field definitions with validation constraints, metadata, and configuration options.
235
236
```python { .api }
237
def Field(default=PydanticUndefined, *, default_factory=None, alias=None,
238
alias_priority=None, validation_alias=None, serialization_alias=None,
239
title=None, field_title_generator=None, description=None, examples=None,
240
exclude=None, discriminator=None, deprecated=None, json_schema_extra=None,
241
frozen=None, validate_default=None, repr=True, init=None, init_var=None,
242
kw_only=None, pattern=None, strict=None, gt=None, ge=None, lt=None, le=None,
243
multiple_of=None, allow_inf_nan=None, max_digits=None, decimal_places=None,
244
min_length=None, max_length=None, **kwargs):
245
"""
246
Create a field definition with validation and metadata.
247
248
Args:
249
default: Default value for the field
250
default_factory: Factory function for default values
251
alias: Alias for the field name
252
alias_priority (int): Priority for alias resolution
253
validation_alias: Alias used during validation
254
serialization_alias: Alias used during serialization
255
title (str): Human-readable title
256
field_title_generator: Function to generate field title
257
description (str): Field description
258
examples: Example values
259
exclude: Whether to exclude from serialization
260
discriminator: Discriminator for union types
261
deprecated: Deprecation information
262
json_schema_extra: Extra JSON schema properties
263
frozen (bool): Whether field is frozen after initialization
264
validate_default (bool): Validate default values
265
repr (bool): Include in repr output
266
init (bool): Include in __init__ method
267
init_var (bool): Mark as init-only variable
268
kw_only (bool): Keyword-only parameter
269
pattern (str): Regex pattern for string validation
270
strict (bool): Enable strict validation
271
gt: Greater than constraint
272
ge: Greater than or equal constraint
273
lt: Less than constraint
274
le: Less than or equal constraint
275
multiple_of: Multiple of constraint
276
allow_inf_nan (bool): Allow infinity and NaN values
277
max_digits (int): Maximum number of digits
278
decimal_places (int): Maximum decimal places
279
min_length (int): Minimum length constraint
280
max_length (int): Maximum length constraint
281
282
Returns:
283
FieldInfo: Field definition object
284
"""
285
```
286
287
### Dynamic Model Creation
288
289
Create pydantic model classes dynamically at runtime.
290
291
```python { .api }
292
def create_model(__model_name, *, __config__=None, __base__=None, __module__=None,
293
__validators__=None, __cls_kwargs__=None, **field_definitions):
294
"""
295
Dynamically create a pydantic model class.
296
297
Args:
298
__model_name (str): Name of the model class
299
__config__: Model configuration
300
__base__: Base class (defaults to BaseModel)
301
__module__ (str): Module name for the class
302
__validators__: Dictionary of validators
303
__cls_kwargs__: Additional class keyword arguments
304
**field_definitions: Field definitions as name=(type, field_info) pairs
305
306
Returns:
307
type: Dynamically created model class
308
"""
309
```
310
311
## Usage Examples
312
313
### Basic Model Definition
314
315
```python
316
from pydantic import BaseModel, Field
317
from typing import Optional
318
319
class Product(BaseModel):
320
id: int
321
name: str = Field(..., min_length=1, max_length=100)
322
price: float = Field(..., gt=0)
323
description: Optional[str] = None
324
in_stock: bool = True
325
326
# Create and validate
327
product = Product(
328
id=1,
329
name="Laptop",
330
price=999.99,
331
description="High-performance laptop"
332
)
333
```
334
335
### RootModel Usage
336
337
```python
338
from pydantic import RootModel
339
from typing import List
340
341
class UserIds(RootModel[List[int]]):
342
root: List[int]
343
344
# Validate list of integers
345
user_ids = UserIds([1, 2, 3, 4])
346
print(user_ids.root) # [1, 2, 3, 4]
347
```
348
349
### Dynamic Model Creation
350
351
```python
352
from pydantic import create_model, Field
353
354
# Create model dynamically
355
DynamicModel = create_model(
356
'DynamicModel',
357
name=(str, Field(..., min_length=1)),
358
age=(int, Field(..., ge=0, le=150))
359
)
360
361
# Use the dynamic model
362
instance = DynamicModel(name="Alice", age=30)
363
```