or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

basic-types.mdcompound-types.mdcontrib-modules.mddynamic-fields.mdexceptions.mdindex.mdmodels.mdnetwork-types.mdutilities.md

models.mddocs/

0

# Model System

1

2

Core model definition and data management functionality in Schematics. The Model class serves as the foundation for defining structured data with validation, providing an ORM-like interface without database coupling.

3

4

## Capabilities

5

6

### Model Definition

7

8

Define structured data models using field declarations with metaclass-based field registration and inheritance.

9

10

```python { .api }

11

class Model:

12

"""

13

Base class for defining structured data models with validation.

14

15

The Model class uses a metaclass (ModelMeta) to register fields and

16

handle inheritance, providing a Django-like model definition experience.

17

"""

18

19

def __init__(self, raw_data=None, trusted_data=None, deserialize_mapping=None,

20

init=True, partial=True, strict=True, validate=False, app_data=None,

21

lazy=False, **kwargs):

22

"""

23

Initialize model instance with optional data.

24

25

Args:

26

raw_data (dict, optional): Initial data to populate the model

27

trusted_data (dict, optional): Pre-validated data

28

deserialize_mapping (dict, optional): Field name mapping

29

init (bool): Whether to initialize field values

30

partial (bool): Whether to allow partial data

31

strict (bool): Whether to enforce strict validation

32

validate (bool): Whether to validate on initialization

33

app_data (dict, optional): Application-specific data

34

lazy (bool): Whether to defer field initialization

35

**kwargs: Additional initialization options

36

"""

37

```

38

39

### Data Import and Validation

40

41

Import raw data into models with automatic type conversion and comprehensive validation.

42

43

```python { .api }

44

def import_data(self, raw_data, recursive=False, **kwargs):

45

"""

46

Import and convert raw data into the model.

47

48

Args:

49

raw_data (dict): Raw data to import

50

recursive (bool): Whether to recursively import nested models

51

**kwargs: Additional import options

52

53

Returns:

54

None

55

56

Raises:

57

ConversionError: If data conversion fails

58

ValidationError: If validation fails

59

"""

60

61

def validate(self, partial=False, convert=True, app_data=None, **kwargs):

62

"""

63

Validate all model data according to field rules.

64

65

Args:

66

partial (bool): Whether to allow partial validation

67

convert (bool): Whether to convert data during validation

68

app_data (dict, optional): Application-specific validation data

69

**kwargs: Additional validation options

70

71

Returns:

72

None

73

74

Raises:

75

ValidationError: If any field validation fails

76

DataError: If multiple validation errors occur

77

"""

78

```

79

80

### Data Export and Serialization

81

82

Export model data in various formats with field filtering and level control.

83

84

```python { .api }

85

def export(self, field_converter=None, role=None, app_data=None, **kwargs):

86

"""

87

Export model data with field filtering and conversion.

88

89

Args:

90

field_converter (callable, optional): Custom field conversion function

91

role (str, optional): Role-based field filtering

92

app_data (dict, optional): Application-specific export data

93

**kwargs: Additional export options including fields, exclude, etc.

94

95

Returns:

96

dict: Exported data

97

"""

98

99

def to_native(self):

100

"""

101

Convert model to native Python objects.

102

103

Returns:

104

dict: Model data as native Python types

105

"""

106

107

def to_primitive(self):

108

"""

109

Convert model to JSON-serializable primitives.

110

111

Returns:

112

dict: Model data as JSON-serializable types

113

"""

114

115

def serialize(self):

116

"""

117

Serialize model to JSON string.

118

119

Returns:

120

str: JSON representation of model data

121

"""

122

```

123

124

### Data Access Methods

125

126

Access model data using dictionary-like and object-like interfaces.

127

128

```python { .api }

129

def get(self, key, default=None):

130

"""

131

Get field value with optional default.

132

133

Args:

134

key (str): Field name

135

default: Default value if field is undefined

136

137

Returns:

138

Field value or default

139

"""

140

141

def keys(self):

142

"""

143

Get all field names.

144

145

Returns:

146

dict_keys: Field names

147

"""

148

149

def items(self):

150

"""

151

Get field name-value pairs.

152

153

Returns:

154

dict_items: Field name-value pairs

155

"""

156

157

def values(self):

158

"""

159

Get all field values.

160

161

Returns:

162

dict_values: Field values

163

"""

164

165

def atoms(self):

166

"""

167

Iterate over field names and native values.

168

169

Yields:

170

tuple: (field_name, native_value) pairs

171

"""

172

```

173

174

### Mock Data Generation

175

176

Generate mock data for testing and development.

177

178

```python { .api }

179

def get_mock_object(self, **overrides):

180

"""

181

Generate mock instance with realistic test data.

182

183

Args:

184

**overrides: Field values to override in mock data

185

186

Returns:

187

Model: New model instance with mock data

188

189

Raises:

190

MockCreationError: If mock generation fails

191

"""

192

```

193

194

### Model Metaclass

195

196

The ModelMeta metaclass handles field registration and model class creation.

197

198

```python { .api }

199

class ModelMeta(type):

200

"""

201

Metaclass for Model classes that registers fields and handles inheritance.

202

203

Automatically discovers field declarations and creates the _fields

204

class attribute mapping field names to field instances.

205

"""

206

```

207

208

### Field Descriptor

209

210

Internal descriptor class for field access on model instances.

211

212

```python { .api }

213

class FieldDescriptor:

214

"""

215

Descriptor that provides field access on model instances.

216

217

Returns field type objects when accessed on model classes,

218

and field values when accessed on model instances.

219

"""

220

221

def __init__(self, name):

222

"""

223

Initialize field descriptor.

224

225

Args:

226

name (str): Field name

227

"""

228

```

229

230

## Usage Examples

231

232

### Basic Model Definition

233

234

```python

235

from schematics.models import Model

236

from schematics.types import StringType, IntType, BooleanType

237

238

class Product(Model):

239

name = StringType(required=True, max_length=100)

240

price = IntType(min_value=0, required=True)

241

in_stock = BooleanType(default=True)

242

243

# Usage

244

product_data = {'name': 'Widget', 'price': 1999}

245

product = Product(product_data)

246

product.validate()

247

print(product.to_primitive()) # {'name': 'Widget', 'price': 1999, 'in_stock': True}

248

```

249

250

### Data Import and Validation

251

252

```python

253

# Import from various sources

254

raw_data = {'name': 'Test Product', 'price': '29.99', 'in_stock': 'true'}

255

256

product = Product()

257

product.import_data(raw_data) # Converts strings to appropriate types

258

product.validate() # Validates all fields

259

260

# Access converted data

261

print(product.name) # 'Test Product'

262

print(product.price) # 2999 (converted from string)

263

print(product.in_stock) # True (converted from string)

264

```

265

266

### Export with Filtering

267

268

```python

269

product = Product({'name': 'Widget', 'price': 1999, 'in_stock': False})

270

271

# Export specific fields only

272

public_data = product.export(fields=['name', 'price'])

273

# {'name': 'Widget', 'price': 1999}

274

275

# Export excluding sensitive fields

276

safe_data = product.export(exclude=['price'])

277

# {'name': 'Widget', 'in_stock': False}

278

```