or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

auth-permissions.mdcontent-negotiation.mddecorators.mdfields-validation.mdgeneric-views.mdindex.mdpagination-filtering.mdrequest-response.mdrouters-urls.mdserializers.mdstatus-exceptions.mdtesting.mdviews-viewsets.md

serializers.mddocs/

0

# Serializers

1

2

Core serialization framework for converting between Python objects and JSON/XML data formats. Serializers handle validation, type conversion, nested relationships, and provide extensive customization options for data transformation.

3

4

## Capabilities

5

6

### Base Serializer

7

8

Foundation class providing minimal serialization interface with core validation and save functionality.

9

10

```python { .api }

11

class BaseSerializer(Field):

12

"""

13

Base serializer class providing core serialization functionality.

14

15

Args:

16

instance: Object instance to serialize (for updates)

17

data: Input data to validate and deserialize

18

many (bool): Handle multiple objects if True

19

context (dict): Additional context for serialization

20

"""

21

def __init__(self, instance=None, data=empty, **kwargs): ...

22

23

def is_valid(self, raise_exception=False):

24

"""

25

Validate input data.

26

27

Args:

28

raise_exception (bool): Raise ValidationError if invalid

29

30

Returns:

31

bool: True if data is valid

32

"""

33

34

def save(self, **kwargs):

35

"""

36

Save validated data by calling create() or update().

37

38

Returns:

39

Object instance created or updated

40

"""

41

42

def create(self, validated_data):

43

"""

44

Create new object instance from validated data.

45

46

Args:

47

validated_data (dict): Validated input data

48

49

Returns:

50

Object instance created

51

"""

52

53

def update(self, instance, validated_data):

54

"""

55

Update existing object instance with validated data.

56

57

Args:

58

instance: Existing object to update

59

validated_data (dict): Validated input data

60

61

Returns:

62

Updated object instance

63

"""

64

65

@property

66

def data(self):

67

"""Serialized representation of the object."""

68

69

@property

70

def errors(self):

71

"""Dictionary of validation errors."""

72

73

@property

74

def validated_data(self):

75

"""Dictionary of validated input data."""

76

```

77

78

### Main Serializer

79

80

Full-featured serializer class with field declaration, validation, and customization capabilities.

81

82

```python { .api }

83

class Serializer(BaseSerializer):

84

"""

85

Main serializer class with declarative field definitions.

86

"""

87

def to_representation(self, instance):

88

"""

89

Convert object instance to native Python datatypes.

90

91

Args:

92

instance: Object to serialize

93

94

Returns:

95

dict: Serialized representation

96

"""

97

98

def to_internal_value(self, data):

99

"""

100

Validate and transform input data to internal Python representation.

101

102

Args:

103

data: Input data to validate

104

105

Returns:

106

dict: Validated data

107

"""

108

109

def validate(self, attrs):

110

"""

111

Perform object-level validation.

112

113

Args:

114

attrs (dict): Field values after individual validation

115

116

Returns:

117

dict: Validated attributes

118

"""

119

```

120

121

### Model Serializer

122

123

Automatically generates fields from Django model definitions with intelligent defaults and relationships.

124

125

```python { .api }

126

class ModelSerializer(Serializer):

127

"""

128

Serializer that automatically generates fields from Django models.

129

"""

130

serializer_field_mapping = {

131

# Django field -> DRF field mappings

132

}

133

134

class Meta:

135

model = None # Django model class

136

fields = None # Fields to include ('__all__' or list)

137

exclude = None # Fields to exclude

138

read_only_fields = None # Read-only field names

139

extra_kwargs = None # Additional field arguments

140

141

def build_field(self, field_name, info, model_class, nested_depth):

142

"""

143

Build individual serializer field from model field.

144

145

Returns:

146

tuple: (field_class, field_kwargs)

147

"""

148

149

def build_relational_field(self, field_name, relation_info):

150

"""

151

Build relational field for model relationships.

152

153

Returns:

154

tuple: (field_class, field_kwargs)

155

"""

156

157

def build_nested_field(self, field_name, relation_info, nested_depth):

158

"""

159

Build nested serializer for related objects.

160

161

Returns:

162

tuple: (field_class, field_kwargs)

163

"""

164

```

165

166

### Hyperlinked Model Serializer

167

168

Model serializer using hyperlinks for object references instead of primary keys.

169

170

```python { .api }

171

class HyperlinkedModelSerializer(ModelSerializer):

172

"""

173

ModelSerializer that uses hyperlinked relationships instead of primary keys.

174

"""

175

serializer_related_field = HyperlinkedRelatedField

176

serializer_url_field = HyperlinkedIdentityField

177

178

url_field_name = 'url' # Field name for object URL

179

180

def build_nested_field(self, field_name, relation_info, nested_depth):

181

"""Build nested field using hyperlinks."""

182

```

183

184

### List Serializer

185

186

Handles serialization of lists/querysets of objects with bulk operations support.

187

188

```python { .api }

189

class ListSerializer(BaseSerializer):

190

"""

191

Serializer for handling lists of objects.

192

"""

193

child = None # Child serializer class

194

allow_empty = True # Allow empty lists

195

max_length = None # Maximum list length

196

min_length = None # Minimum list length

197

198

def create(self, validated_data):

199

"""

200

Create multiple objects from list of validated data.

201

202

Args:

203

validated_data (list): List of validated data dicts

204

205

Returns:

206

list: Created object instances

207

"""

208

209

def update(self, instance, validated_data):

210

"""

211

Update multiple objects from list of validated data.

212

213

Args:

214

instance (list): Existing objects to update

215

validated_data (list): List of validated data dicts

216

217

Returns:

218

list: Updated object instances

219

"""

220

```

221

222

### Validation Methods

223

224

Custom validation methods for serializers provide field-level and object-level validation.

225

226

```python { .api }

227

# Field-level validation method pattern

228

def validate_<field_name>(self, value):

229

"""

230

Validate individual field value.

231

232

Args:

233

value: Field value to validate

234

235

Returns:

236

Validated value

237

238

Raises:

239

ValidationError: If validation fails

240

"""

241

242

# Object-level validation

243

def validate(self, attrs):

244

"""

245

Validate entire object after field validation.

246

247

Args:

248

attrs (dict): Dictionary of field values

249

250

Returns:

251

dict: Validated attributes dictionary

252

253

Raises:

254

ValidationError: If validation fails

255

"""

256

```

257

258

## Usage Examples

259

260

### Basic Serializer Usage

261

262

```python

263

from rest_framework import serializers

264

265

class BookSerializer(serializers.Serializer):

266

title = serializers.CharField(max_length=100)

267

author = serializers.CharField(max_length=50)

268

publication_date = serializers.DateField()

269

isbn = serializers.CharField(max_length=13)

270

271

def validate_isbn(self, value):

272

if len(value) != 13:

273

raise serializers.ValidationError("ISBN must be 13 characters")

274

return value

275

276

def validate(self, data):

277

if data['publication_date'] > timezone.now().date():

278

raise serializers.ValidationError("Publication date cannot be in the future")

279

return data

280

281

# Serializing data

282

book_data = {'title': 'Django Guide', 'author': 'Jane Doe', 'publication_date': '2023-01-01', 'isbn': '1234567890123'}

283

serializer = BookSerializer(data=book_data)

284

if serializer.is_valid():

285

print(serializer.validated_data)

286

```

287

288

### Model Serializer Usage

289

290

```python

291

from django.db import models

292

from rest_framework import serializers

293

294

class Book(models.Model):

295

title = models.CharField(max_length=100)

296

author = models.CharField(max_length=50)

297

publication_date = models.DateField()

298

isbn = models.CharField(max_length=13, unique=True)

299

300

class BookSerializer(serializers.ModelSerializer):

301

class Meta:

302

model = Book

303

fields = ['id', 'title', 'author', 'publication_date', 'isbn']

304

read_only_fields = ['id']

305

extra_kwargs = {

306

'isbn': {'validators': [isbn_validator]}

307

}

308

309

# Create object

310

serializer = BookSerializer(data=book_data)

311

if serializer.is_valid():

312

book = serializer.save()

313

314

# Update object

315

book = Book.objects.get(pk=1)

316

serializer = BookSerializer(book, data=updated_data, partial=True)

317

if serializer.is_valid():

318

updated_book = serializer.save()

319

```

320

321

### Nested Serialization

322

323

```python

324

class AuthorSerializer(serializers.ModelSerializer):

325

class Meta:

326

model = Author

327

fields = ['id', 'name', 'email']

328

329

class BookSerializer(serializers.ModelSerializer):

330

author = AuthorSerializer(read_only=True)

331

author_id = serializers.IntegerField(write_only=True)

332

333

class Meta:

334

model = Book

335

fields = ['id', 'title', 'author', 'author_id', 'publication_date']

336

```

337

338

## Constants

339

340

```python { .api }

341

# Special values

342

ALL_FIELDS = '__all__' # Include all model fields

343

LIST_SERIALIZER_KWARGS = [ # Arguments passed to ListSerializer

344

'allow_empty', 'child', 'max_length', 'min_length'

345

]

346

347

# Utility functions

348

def as_serializer_error(exc):

349

"""Convert exception to serializer error format."""

350

351

def raise_errors_on_nested_writes(method_name, serializer, validated_data):

352

"""Prevent nested writes without explicit handling."""

353

```