Debian Codegraph @

docs/api-guide/serializers.md

raw
1 ---
2 source:
3 - serializers.py
4 ---
5
6 > Expanding the usefulness of the serializers is something that we would
7 like to address. However, it's not a trivial problem, and it
8 will take some serious design work.
9 >
10 > — Russell Keith-Magee, [Django users group][cite]
11
12 Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into `JSON`, `XML` or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
13
14 The serializers in REST framework work very similarly to Django's `Form` and `ModelForm` classes. We provide a `Serializer` class which gives you a powerful, generic way to control the output of your responses, as well as a `ModelSerializer` class which provides a useful shortcut for creating serializers that deal with model instances and querysets.
15
16 ## Serializers
17
18 ### Declaring Serializers
19
20 Let's start by creating a simple object we can use for example purposes:
21
22 from datetime import datetime
23
24 class Comment:
25 def __init__(self, email, content, created=None):
26 self.email = email
27 self.content = content
28 self.created = created or datetime.now()
29
30 comment = Comment(email='[email protected]', content='foo bar')
31
32 We'll declare a serializer that we can use to serialize and deserialize data that corresponds to `Comment` objects.
33
34 Declaring a serializer looks very similar to declaring a form:
35
36 from rest_framework import serializers
37
38 class CommentSerializer(serializers.Serializer):
39 email = serializers.EmailField()
40 content = serializers.CharField(max_length=200)
41 created = serializers.DateTimeField()
42
43 ### Serializing objects
44
45 We can now use `CommentSerializer` to serialize a comment, or list of comments. Again, using the `Serializer` class looks a lot like using a `Form` class.
46
47 serializer = CommentSerializer(comment)
48 serializer.data
49 # {'email': '[email protected]', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}
50
51 At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`.
52
53 from rest_framework.renderers import JSONRenderer
54
55 json = JSONRenderer().render(serializer.data)
56 json
57 # b'{"email":"[email protected]","content":"foo bar","created":"2016-01-27T15:17:10.375877"}'
58
59 ### Deserializing objects
60
61 Deserialization is similar. First we parse a stream into Python native datatypes...
62
63 import io
64 from rest_framework.parsers import JSONParser
65
66 stream = io.BytesIO(json)
67 data = JSONParser().parse(stream)
68
69 ...then we restore those native datatypes into a dictionary of validated data.
70
71 serializer = CommentSerializer(data=data)
72 serializer.is_valid()
73 # True
74 serializer.validated_data
75 # {'content': 'foo bar', 'email': '[email protected]', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}
76
77 ### Saving instances
78
79 If we want to be able to return complete object instances based on the validated data we need to implement one or both of the `.create()` and `.update()` methods. For example:
80
81 class CommentSerializer(serializers.Serializer):
82 email = serializers.EmailField()
83 content = serializers.CharField(max_length=200)
84 created = serializers.DateTimeField()
85
86 def create(self, validated_data):
87 return Comment(**validated_data)
88
89 def update(self, instance, validated_data):
90 instance.email = validated_data.get('email', instance.email)
91 instance.content = validated_data.get('content', instance.content)
92 instance.created = validated_data.get('created', instance.created)
93 return instance
94
95 If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if `Comment` was a Django model, the methods might look like this:
96
97 def create(self, validated_data):
98 return Comment.objects.create(**validated_data)
99
100 def update(self, instance, validated_data):
101 instance.email = validated_data.get('email', instance.email)
102 instance.content = validated_data.get('content', instance.content)
103 instance.created = validated_data.get('created', instance.created)
104 instance.save()
105 return instance
106
107 Now when deserializing data, we can call `.save()` to return an object instance, based on the validated data.
108
109 comment = serializer.save()
110
111 Calling `.save()` will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class:
112
113 # .save() will create a new instance.
114 serializer = CommentSerializer(data=data)
115
116 # .save() will update the existing `comment` instance.
117 serializer = CommentSerializer(comment, data=data)
118
119 Both the `.create()` and `.update()` methods are optional. You can implement either none, one, or both of them, depending on the use-case for your serializer class.
120
121 #### Passing additional attributes to `.save()`
122
123 Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data.
124
125 You can do so by including additional keyword arguments when calling `.save()`. For example:
126
127 serializer.save(owner=request.user)
128
129 Any additional keyword arguments will be included in the `validated_data` argument when `.create()` or `.update()` are called.
130
131 #### Overriding `.save()` directly.
132
133 In some cases the `.create()` and `.update()` method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message.
134
135 In these cases you might instead choose to override `.save()` directly, as being more readable and meaningful.
136
137 For example:
138
139 class ContactForm(serializers.Serializer):
140 email = serializers.EmailField()
141 message = serializers.CharField()
142
143 def save(self):
144 email = self.validated_data['email']
145 message = self.validated_data['message']
146 send_email(from=email, message=message)
147
148 Note that in the case above we're now having to access the serializer `.validated_data` property directly.
149
150 ### Validation
151
152 When deserializing data, you always need to call `is_valid()` before attempting to access the validated data, or save an object instance. If any validation errors occur, the `.errors` property will contain a dictionary representing the resulting error messages. For example:
153
154 serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'})
155 serializer.is_valid()
156 # False
157 serializer.errors
158 # {'email': ['Enter a valid email address.'], 'created': ['This field is required.']}
159
160 Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors. The name of the `non_field_errors` key may be customized using the `NON_FIELD_ERRORS_KEY` REST framework setting.
161
162 When deserializing a list of items, errors are returned as a dictionary keyed by the indexes of invalid items. Valid items are omitted from the dictionary.
163
164 To temporarily use the list-based format from versions before REST framework 3.18, set `LIST_SERIALIZER_ERRORS_AS_DICT` to `False`. This format includes an empty dictionary for each valid item and is deprecated. It will be removed in REST framework 3.20.
165
166 #### Raising an exception on invalid data
167
168 The `.is_valid()` method takes an optional `raise_exception` flag that will cause it to raise a `serializers.ValidationError` exception if there are validation errors.
169
170 These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return `HTTP 400 Bad Request` responses by default.
171
172 # Return a 400 response if the data was invalid.
173 serializer.is_valid(raise_exception=True)
174
175 #### Field-level validation
176
177 You can specify custom field-level validation by adding `.validate_<field_name>` methods to your `Serializer` subclass. These are similar to the `.clean_<field_name>` methods on Django forms.
178
179 These methods take a single argument, which is the field value that requires validation.
180
181 Your `validate_<field_name>` methods should return the validated value or raise a `serializers.ValidationError`. For example:
182
183 from rest_framework import serializers
184
185 class BlogPostSerializer(serializers.Serializer):
186 title = serializers.CharField(max_length=100)
187 content = serializers.CharField()
188
189 def validate_title(self, value):
190 """
191 Check that the blog post is about Django.
192 """
193 if 'django' not in value.lower():
194 raise serializers.ValidationError("Blog post is not about Django")
195 return value
196
197 !!! note
198 If your `<field_name>` is declared on your serializer with the parameter `required=False` then this validation step will not take place if the field is not included.
199
200 #### Object-level validation
201
202 To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is a dictionary of field values. It should raise a `serializers.ValidationError` if necessary, or just return the validated values. For example:
203
204 from rest_framework import serializers
205
206 class EventSerializer(serializers.Serializer):
207 description = serializers.CharField(max_length=100)
208 start = serializers.DateTimeField()
209 finish = serializers.DateTimeField()
210
211 def validate(self, data):
212 """
213 Check that start is before finish.
214 """
215 if data['start'] > data['finish']:
216 raise serializers.ValidationError("finish must occur after start")
217 return data
218
219 !!! note
220 **Object-Level Validation and Partial Updates**
221
222 When performing a **partial update** (`PATCH`), the `data` dictionary passed to the `validate()` method will **only contain the fields** provided in the request. If your validation logic depends on multiple fields, you must account for cases where some fields are missing from `data`.
223
224 To access fields not included in the partial update, you should retrieve them from the existing object instance using `self.instance`:
225
226 ```python
227 def validate(self, data):
228 # Check if "status" is being updated, or use the existing value
229 status = data.get("status", self.instance.status)
230
231 # Check if "price" is being updated, or use the existing value
232 price = data.get("price", self.instance.price)
233
234 if status == "active" and price <= 0:
235 raise serializers.ValidationError("Active products must have a price.")
236 return data
237 ```
238
239 #### Validators
240
241 Individual fields on a serializer can include validators, by declaring them on the field instance, for example:
242
243 def multiple_of_ten(value):
244 if value % 10 != 0:
245 raise serializers.ValidationError('Not a multiple of ten')
246
247 class GameRecord(serializers.Serializer):
248 score = serializers.IntegerField(validators=[multiple_of_ten])
249 ...
250
251 Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner `Meta` class, like so:
252
253 class EventSerializer(serializers.Serializer):
254 name = serializers.CharField()
255 room_number = serializers.ChoiceField(choices=[101, 102, 103, 201])
256 date = serializers.DateField()
257
258 class Meta:
259 # Each room only has one event per day.
260 validators = [
261 UniqueTogetherValidator(
262 queryset=Event.objects.all(),
263 fields=['room_number', 'date']
264 )
265 ]
266
267 For more information see the [validators documentation](validators.md).
268
269 ### Accessing the initial data and instance
270
271 When passing an initial object or queryset to a serializer instance, the object will be made available as `.instance`. If no initial object is passed then the `.instance` attribute will be `None`.
272
273 When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the `data` keyword argument is not passed then the `.initial_data` attribute will not exist.
274
275 ### Partial updates
276
277 By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the `partial` argument in order to allow partial updates.
278
279 # Update `comment` with partial data
280 serializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)
281
282 ### Dealing with nested objects
283
284 The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers.
285
286 The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another.
287
288 class UserSerializer(serializers.Serializer):
289 email = serializers.EmailField()
290 username = serializers.CharField(max_length=100)
291
292 class CommentSerializer(serializers.Serializer):
293 user = UserSerializer()
294 content = serializers.CharField(max_length=200)
295 created = serializers.DateTimeField()
296
297 If a nested representation may optionally accept the `None` value you should pass the `required=False` flag to the nested serializer.
298
299 class CommentSerializer(serializers.Serializer):
300 user = UserSerializer(required=False) # May be an anonymous user.
301 content = serializers.CharField(max_length=200)
302 created = serializers.DateTimeField()
303
304 Similarly if a nested representation should be a list of items, you should pass the `many=True` flag to the nested serializer.
305
306 class CommentSerializer(serializers.Serializer):
307 user = UserSerializer(required=False)
308 edits = EditItemSerializer(many=True) # A nested list of 'edit' items.
309 content = serializers.CharField(max_length=200)
310 created = serializers.DateTimeField()
311
312 ### Writable nested representations
313
314 When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object.
315
316 serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'})
317 serializer.is_valid()
318 # False
319 serializer.errors
320 # {'user': {'email': ['Enter a valid email address.']}, 'created': ['This field is required.']}
321
322 Similarly, the `.validated_data` property will include nested data structures.
323
324 #### Writing `.create()` methods for nested representations
325
326 If you're supporting writable nested representations you'll need to write `.create()` or `.update()` methods that handle saving multiple objects.
327
328 The following example demonstrates how you might handle creating a user with a nested profile object.
329
330 class UserSerializer(serializers.ModelSerializer):
331 profile = ProfileSerializer()
332
333 class Meta:
334 model = User
335 fields = ['username', 'email', 'profile']
336
337 def create(self, validated_data):
338 profile_data = validated_data.pop('profile')
339 user = User.objects.create(**validated_data)
340 Profile.objects.create(user=user, **profile_data)
341 return user
342
343 #### Writing `.update()` methods for nested representations
344
345 For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is `None`, or not provided, which of the following should occur?
346
347 * Set the relationship to `NULL` in the database.
348 * Delete the associated instance.
349 * Ignore the data and leave the instance as it is.
350 * Raise a validation error.
351
352 Here's an example for an `.update()` method on our previous `UserSerializer` class.
353
354 def update(self, instance, validated_data):
355 profile_data = validated_data.pop('profile')
356 # Unless the application properly enforces that this field is
357 # always set, the following could raise a `DoesNotExist`, which
358 # would need to be handled.
359 profile = instance.profile
360
361 instance.username = validated_data.get('username', instance.username)
362 instance.email = validated_data.get('email', instance.email)
363 instance.save()
364
365 profile.is_premium_member = profile_data.get(
366 'is_premium_member',
367 profile.is_premium_member
368 )
369 profile.has_support_contract = profile_data.get(
370 'has_support_contract',
371 profile.has_support_contract
372 )
373 profile.save()
374
375 return instance
376
377 Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default `ModelSerializer` `.create()` and `.update()` methods do not include support for writable nested representations.
378
379 There are however, third-party packages available such as [DRF Writable Nested][thirdparty-writable-nested] that support automatic writable nested representations.
380
381 #### Handling saving related instances in model manager classes
382
383 An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances.
384
385 For example, suppose we wanted to ensure that `User` instances and `Profile` instances are always created together as a pair. We might write a custom manager class that looks something like this:
386
387 class UserManager(models.Manager):
388 ...
389
390 def create(self, username, email, is_premium_member=False, has_support_contract=False):
391 user = User(username=username, email=email)
392 user.save()
393 profile = Profile(
394 user=user,
395 is_premium_member=is_premium_member,
396 has_support_contract=has_support_contract
397 )
398 profile.save()
399 return user
400
401 This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our `.create()` method on the serializer class can now be re-written to use the new manager method.
402
403 def create(self, validated_data):
404 return User.objects.create(
405 username=validated_data['username'],
406 email=validated_data['email'],
407 is_premium_member=validated_data['profile']['is_premium_member'],
408 has_support_contract=validated_data['profile']['has_support_contract']
409 )
410
411 For more details on this approach see the Django documentation on [model managers][model-managers], and [this blogpost on using model and manager classes][encapsulation-blogpost].
412
413 ### Dealing with multiple objects
414
415 The `Serializer` class can also handle serializing or deserializing lists of objects.
416
417 #### Serializing multiple objects
418
419 To serialize a queryset or list of objects instead of a single object instance, you should pass the `many=True` flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
420
421 queryset = Book.objects.all()
422 serializer = BookSerializer(queryset, many=True)
423 serializer.data
424 # [
425 # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
426 # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
427 # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
428 # ]
429
430 #### Deserializing multiple objects
431
432 The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the [ListSerializer](#listserializer) documentation below.
433
434 ### Including extra context
435
436 There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs.
437
438 You can provide arbitrary additional context by passing a `context` argument when instantiating the serializer. For example:
439
440 serializer = AccountSerializer(account, context={'request': request})
441 serializer.data
442 # {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
443
444 The context dictionary can be used within any serializer field logic, such as a custom `.to_representation()` method, by accessing the `self.context` attribute.
445
446 ---
447
448 ## ModelSerializer
449
450 Often you'll want serializer classes that map closely to Django model definitions.
451
452 The `ModelSerializer` class provides a shortcut that lets you automatically create a `Serializer` class with fields that correspond to the Model fields.
453
454 **The `ModelSerializer` class is the same as a regular `Serializer` class, except that**:
455
456 * It will automatically generate a set of fields for you, based on the model.
457 * It will automatically generate validators for the serializer, such as unique_together validators.
458 * It includes simple default implementations of `.create()` and `.update()`.
459
460 Declaring a `ModelSerializer` looks like this:
461
462 class AccountSerializer(serializers.ModelSerializer):
463 class Meta:
464 model = Account
465 fields = ['id', 'account_name', 'users', 'created']
466
467 By default, all the model fields on the class will be mapped to a corresponding serializer fields.
468
469 Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Reverse relationships are not included by default unless explicitly included as specified in the [serializer relations][relations] documentation.
470
471 ### Inspecting a `ModelSerializer`
472
473 Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with `ModelSerializers` where you want to determine what set of fields and validators are being automatically created for you.
474
475 To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation…
476
477 >>> from myapp.serializers import AccountSerializer
478 >>> serializer = AccountSerializer()
479 >>> print(repr(serializer))
480 AccountSerializer():
481 id = IntegerField(label='ID', read_only=True)
482 name = CharField(allow_blank=True, max_length=100, required=False)
483 owner = PrimaryKeyRelatedField(queryset=User.objects.all())
484
485 ### Specifying which fields to include
486
487 If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`. It is strongly recommended that you explicitly set all fields that should be serialized using the `fields` attribute. This will make it less likely to result in unintentionally exposing data when your models change.
488
489 For example:
490
491 class AccountSerializer(serializers.ModelSerializer):
492 class Meta:
493 model = Account
494 fields = ['id', 'account_name', 'users', 'created']
495
496 You can also set the `fields` attribute to the special value `'__all__'` to indicate that all fields in the model should be used.
497
498 For example:
499
500 class AccountSerializer(serializers.ModelSerializer):
501 class Meta:
502 model = Account
503 fields = '__all__'
504
505 You can set the `exclude` attribute to a list of fields to be excluded from the serializer.
506
507 For example:
508
509 class AccountSerializer(serializers.ModelSerializer):
510 class Meta:
511 model = Account
512 exclude = ['users']
513
514 In the example above, if the `Account` model had 3 fields `account_name`, `users`, and `created`, this will result in the fields `account_name` and `created` to be serialized.
515
516 The names in the `fields` and `exclude` attributes will normally map to model fields on the model class.
517
518 Alternatively names in the `fields` options can map to properties or methods which take no arguments that exist on the model class.
519
520 Since version 3.3.0, it is **mandatory** to provide one of the attributes `fields` or `exclude`.
521
522 ### Specifying nested serialization
523
524 The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option:
525
526 class AccountSerializer(serializers.ModelSerializer):
527 class Meta:
528 model = Account
529 fields = ['id', 'account_name', 'users', 'created']
530 depth = 1
531
532 The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation.
533
534 If you want to customize the way the serialization is done you'll need to define the field yourself.
535
536 ### Specifying fields explicitly
537
538 You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class.
539
540 class AccountSerializer(serializers.ModelSerializer):
541 url = serializers.CharField(source='get_absolute_url', read_only=True)
542 groups = serializers.PrimaryKeyRelatedField(many=True)
543
544 class Meta:
545 model = Account
546 fields = ['url', 'groups']
547
548 Extra fields can correspond to any property or callable on the model.
549
550 ### Specifying read only fields
551
552 You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the shortcut Meta option, `read_only_fields`.
553
554 This option should be a list or tuple of field names, and is declared as follows:
555
556 class AccountSerializer(serializers.ModelSerializer):
557 class Meta:
558 model = Account
559 fields = ['id', 'account_name', 'users', 'created']
560 read_only_fields = ['account_name']
561
562 Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option.
563
564 Please keep in mind that, if a field has already been explicitly declared on the serializer class (or a parent class), then the `read_only_fields` option will not apply to that field. Set `read_only=True` on the field itself instead.
565
566 !!! note
567 There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user.
568
569 The right way to deal with this is to specify the field explicitly on the serializer, providing both the `read_only=True` and `default=…` keyword arguments.
570
571 One example of this is a read-only relation to the currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so:
572
573 user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
574
575 Please review the [Validators Documentation](/api-guide/validators/) for details on the [UniqueTogetherValidator](/api-guide/validators/#uniquetogethervalidator) and [CurrentUserDefault](/api-guide/validators/#currentuserdefault) classes.
576
577 ### Additional keyword arguments
578
579 There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. As in the case of `read_only_fields`, this means you do not need to explicitly declare the field on the serializer.
580
581 This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:
582
583 class CreateUserSerializer(serializers.ModelSerializer):
584 class Meta:
585 model = User
586 fields = ['email', 'username', 'password']
587 extra_kwargs = {'password': {'write_only': True}}
588
589 def create(self, validated_data):
590 user = User(
591 email=validated_data['email'],
592 username=validated_data['username']
593 )
594 user.set_password(validated_data['password'])
595 user.save()
596 return user
597
598 Please keep in mind that, if the field has already been explicitly declared on the serializer class, then the `extra_kwargs` option will be ignored. The same is true of `read_only_fields`, which is implemented using `extra_kwargs`.
599
600 ### Relational fields
601
602 When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for `ModelSerializer` is to use the primary keys of the related instances.
603
604 Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation.
605
606 For full details see the [serializer relations][relations] documentation.
607
608 ### Customizing field mappings
609
610 The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer.
611
612 Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model.
613
614 #### `serializer_field_mapping`
615
616 A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field.
617
618 #### `serializer_related_field`
619
620 This property should be the serializer field class, that is used for relational fields by default.
621
622 For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`.
623
624 For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`.
625
626 #### `serializer_url_field`
627
628 The serializer field class that should be used for any `url` field on the serializer.
629
630 Defaults to `serializers.HyperlinkedIdentityField`
631
632 #### `serializer_choice_field`
633
634 The serializer field class that should be used for any choice fields on the serializer.
635
636 Defaults to `serializers.ChoiceField`
637
638 #### The field_class and field_kwargs API
639
640 The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`.
641
642 #### `build_standard_field(self, field_name, model_field)`
643
644 Called to generate a serializer field that maps to a standard model field.
645
646 The default implementation returns a serializer class based on the `serializer_field_mapping` attribute.
647
648 #### `build_relational_field(self, field_name, relation_info)`
649
650 Called to generate a serializer field that maps to a relational model field.
651
652 The default implementation returns a serializer class based on the `serializer_related_field` attribute.
653
654 The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
655
656 #### `build_nested_field(self, field_name, relation_info, nested_depth)`
657
658 Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set.
659
660 The default implementation dynamically creates a nested serializer class based on either `ModelSerializer` or `HyperlinkedModelSerializer`.
661
662 The `nested_depth` will be the value of the `depth` option, minus one.
663
664 The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties.
665
666 #### `build_property_field(self, field_name, model_class)`
667
668 Called to generate a serializer field that maps to a property or zero-argument method on the model class.
669
670 The default implementation returns a `ReadOnlyField` class.
671
672 #### `build_url_field(self, field_name, model_class)`
673
674 Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class.
675
676 #### `build_unknown_field(self, field_name, model_class)`
677
678 Called when the field name did not map to any model field or model property.
679 The default implementation raises an error, although subclasses may customize this behavior.
680
681 ---
682
683 ## HyperlinkedModelSerializer
684
685 The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` class except that it uses hyperlinks to represent relationships, rather than primary keys.
686
687 By default the serializer will include a `url` field instead of a primary key field.
688
689 The url field will be represented using a `HyperlinkedIdentityField` serializer field, and any relationships on the model will be represented using a `HyperlinkedRelatedField` serializer field.
690
691 You can explicitly include the primary key by adding it to the `fields` option, for example:
692
693 class AccountSerializer(serializers.HyperlinkedModelSerializer):
694 class Meta:
695 model = Account
696 fields = ['url', 'id', 'account_name', 'users', 'created']
697
698 ### Absolute and relative URLs
699
700 When instantiating a `HyperlinkedModelSerializer` you must include the current
701 `request` in the serializer context, for example:
702
703 serializer = AccountSerializer(queryset, context={'request': request})
704
705 Doing so will ensure that the hyperlinks can include an appropriate hostname,
706 so that the resulting representation uses fully qualified URLs, such as:
707
708 http://api.example.com/accounts/1/
709
710 Rather than relative URLs, such as:
711
712 /accounts/1/
713
714 If you *do* want to use relative URLs, you should explicitly pass `{'request': None}`
715 in the serializer context.
716
717 ### How hyperlinked views are determined
718
719 There needs to be a way of determining which views should be used for hyperlinking to model instances.
720
721 By default hyperlinks are expected to correspond to a view name that matches the style `'{model_name}-detail'`, and looks up the instance by a `pk` keyword argument.
722
723 You can override a URL field view name and lookup field by using either, or both of, the `view_name` and `lookup_field` options in the `extra_kwargs` setting, like so:
724
725 class AccountSerializer(serializers.HyperlinkedModelSerializer):
726 class Meta:
727 model = Account
728 fields = ['url', 'account_name', 'users', 'created']
729 extra_kwargs = {
730 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'},
731 'users': {'lookup_field': 'username'}
732 }
733
734 Alternatively you can set the fields on the serializer explicitly. For example:
735
736 class AccountSerializer(serializers.HyperlinkedModelSerializer):
737 url = serializers.HyperlinkedIdentityField(
738 view_name='accounts',
739 lookup_field='slug'
740 )
741 users = serializers.HyperlinkedRelatedField(
742 view_name='user-detail',
743 lookup_field='username',
744 many=True,
745 read_only=True
746 )
747
748 class Meta:
749 model = Account
750 fields = ['url', 'account_name', 'users', 'created']
751
752 ---
753
754 **Tip**: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the `repr` of a `HyperlinkedModelSerializer` instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too.
755
756 ---
757
758 ### Changing the URL field name
759
760 The name of the URL field defaults to 'url'. You can override this globally, by using the `URL_FIELD_NAME` setting.
761
762 ---
763
764 ## ListSerializer
765
766 The `ListSerializer` class provides the behavior for serializing and validating multiple objects at once. You won't *typically* need to use `ListSerializer` directly, but should instead simply pass `many=True` when instantiating a serializer.
767
768 When a serializer is instantiated and `many=True` is passed, a `ListSerializer` instance will be created. The serializer class then becomes a child of the parent `ListSerializer`
769
770 The following argument can also be passed to a `ListSerializer` field or a serializer that is passed `many=True`:
771
772 - `allow_empty`: this is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input.
773
774 - `max_length`: this is `None` by default, but can be set to a positive integer if you want to validate that the list contains no more than this number of elements.
775
776 - `min_length`: this is `None` by default, but can be set to a positive integer if you want to validate that the list contains no fewer than this number of elements.
777
778 ### Customizing `ListSerializer` behavior
779
780 There *are* a few use cases when you might want to customize the `ListSerializer` behavior. For example:
781
782 * You want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list.
783 * You want to customize the create or update behavior of multiple objects.
784
785 For these cases you can modify the class that is used when `many=True` is passed, by using the `list_serializer_class` option on the serializer `Meta` class.
786
787 For example:
788
789 class CustomListSerializer(serializers.ListSerializer):
790 ...
791
792 class CustomSerializer(serializers.Serializer):
793 ...
794 class Meta:
795 list_serializer_class = CustomListSerializer
796
797 ### Customizing multiple create
798
799 The default implementation for multiple object creation is to simply call `.create()` for each item in the list. If you want to customize this behavior, you'll need to customize the `.create()` method on `ListSerializer` class that is used when `many=True` is passed.
800
801 For example:
802
803 class BookListSerializer(serializers.ListSerializer):
804 def create(self, validated_data):
805 books = [Book(**item) for item in validated_data]
806 return Book.objects.bulk_create(books)
807
808 class BookSerializer(serializers.Serializer):
809 ...
810 class Meta:
811 list_serializer_class = BookListSerializer
812
813 ### Customizing multiple update
814
815 By default the `ListSerializer` class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous.
816
817 To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind:
818
819 * How do you determine which instance should be updated for each item in the list of data?
820 * How should insertions be handled? Are they invalid, or do they create new objects?
821 * How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid?
822 * How should ordering be handled? Does changing the position of two items imply any state change or is it ignored?
823
824 You will need to add an explicit `id` field to the instance serializer. The default implicitly-generated `id` field is marked as `read_only`. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's `update` method.
825
826 Here's an example of how you might choose to implement multiple updates:
827
828 class BookListSerializer(serializers.ListSerializer):
829 def update(self, instance, validated_data):
830 # Maps for id->instance and id->data item.
831 book_mapping = {book.id: book for book in instance}
832 data_mapping = {item['id']: item for item in validated_data}
833
834 # Perform creations and updates.
835 ret = []
836 for book_id, data in data_mapping.items():
837 book = book_mapping.get(book_id, None)
838 if book is None:
839 ret.append(self.child.create(data))
840 else:
841 ret.append(self.child.update(book, data))
842
843 # Perform deletions.
844 for book_id, book in book_mapping.items():
845 if book_id not in data_mapping:
846 book.delete()
847
848 return ret
849
850 class BookSerializer(serializers.Serializer):
851 # We need to identify elements in the list using their primary key,
852 # so use a writable field here, rather than the default which would be read-only.
853 id = serializers.IntegerField()
854 ...
855
856 class Meta:
857 list_serializer_class = BookListSerializer
858
859 If the child serializer includes uniqueness validators (`UniqueValidator`, `UniqueTogetherValidator`, or the
860 `UniqueForDateValidator` family), they need to know which object each item in the list is updating, so
861 that the object itself is not reported as a uniqueness conflict. By default the child serializer's
862 `.instance` is the whole queryset or list that was passed to the list serializer, so these validators will
863 raise a `RuntimeError` during a multiple update. To support this, override `run_child_validation()` on
864 your `ListSerializer` subclass to set the child's `.instance` and `.initial_data` for each item before
865 validation. For example, if `self.instance` is a queryset:
866
867 class BookListSerializer(serializers.ListSerializer):
868 def run_child_validation(self, data):
869 # `.instance` stays `None` for items that do not exist yet, and
870 # for malformed items, which child validation will then reject
871 # as usual.
872 self.child.instance = None
873 try:
874 self.child.instance = self.instance.filter(pk=data['id']).first()
875 except (TypeError, KeyError, ValueError):
876 pass
877 self.child.initial_data = data
878 return super().run_child_validation(data)
879
880 def update(self, instance, validated_data):
881 ...
882
883 ### Customizing ListSerializer initialization
884
885 When a serializer with `many=True` is instantiated, we need to determine which arguments and keyword arguments should be passed to the `.__init__()` method for both the child `Serializer` class, and for the parent `ListSerializer` class.
886
887 The default implementation is to pass all arguments to both classes, except for `validators`, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class.
888
889 Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when `many=True` is passed. You can do so by using the `many_init` class method.
890
891 @classmethod
892 def many_init(cls, *args, **kwargs):
893 # Instantiate the child serializer.
894 kwargs['child'] = cls()
895 # Instantiate the parent list serializer.
896 return CustomListSerializer(*args, **kwargs)
897
898 ---
899
900 ## BaseSerializer
901
902 `BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles.
903
904 This class implements the same basic API as the `Serializer` class:
905
906 * `.data` - Returns the outgoing primitive representation.
907 * `.is_valid()` - Deserializes and validates incoming data.
908 * `.validated_data` - Returns the validated incoming data.
909 * `.errors` - Returns any errors during validation.
910 * `.save()` - Persists the validated data into an object instance.
911
912 There are four methods that can be overridden, depending on what functionality you want the serializer class to support:
913
914 * `.to_representation()` - Override this to support serialization, for read operations.
915 * `.to_internal_value()` - Override this to support deserialization, for write operations.
916 * `.create()` and `.update()` - Override either or both of these to support saving instances.
917
918 Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class-based views exactly as you would for a regular `Serializer` or `ModelSerializer`.
919
920 The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input.
921
922 ### Read-only `BaseSerializer` classes
923
924 To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model:
925
926 class HighScore(models.Model):
927 created = models.DateTimeField(auto_now_add=True)
928 player_name = models.CharField(max_length=10)
929 score = models.IntegerField()
930
931 It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types.
932
933 class HighScoreSerializer(serializers.BaseSerializer):
934 def to_representation(self, instance):
935 return {
936 'score': instance.score,
937 'player_name': instance.player_name
938 }
939
940 We can now use this class to serialize single `HighScore` instances:
941
942 @api_view(['GET'])
943 def high_score(request, pk):
944 instance = HighScore.objects.get(pk=pk)
945 serializer = HighScoreSerializer(instance)
946 return Response(serializer.data)
947
948 Or use it to serialize multiple instances:
949
950 @api_view(['GET'])
951 def all_high_scores(request):
952 queryset = HighScore.objects.order_by('-score')
953 serializer = HighScoreSerializer(queryset, many=True)
954 return Response(serializer.data)
955
956 ### Read-write `BaseSerializer` classes
957
958 To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `serializers.ValidationError` if the supplied data is in an incorrect format.
959
960 Once you've implemented `.to_internal_value()`, the basic validation API will be available on the serializer, and you will be able to use `.is_valid()`, `.validated_data` and `.errors`.
961
962 If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods.
963
964 Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations.
965
966 class HighScoreSerializer(serializers.BaseSerializer):
967 def to_internal_value(self, data):
968 score = data.get('score')
969 player_name = data.get('player_name')
970
971 # Perform the data validation.
972 if not score:
973 raise serializers.ValidationError({
974 'score': 'This field is required.'
975 })
976 if not player_name:
977 raise serializers.ValidationError({
978 'player_name': 'This field is required.'
979 })
980 if len(player_name) > 10:
981 raise serializers.ValidationError({
982 'player_name': 'May not be more than 10 characters.'
983 })
984
985 # Return the validated values. This will be available as
986 # the `.validated_data` property.
987 return {
988 'score': int(score),
989 'player_name': player_name
990 }
991
992 def to_representation(self, instance):
993 return {
994 'score': instance.score,
995 'player_name': instance.player_name
996 }
997
998 def create(self, validated_data):
999 return HighScore.objects.create(**validated_data)
1000
1001 ### Creating new base classes
1002
1003 The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends.
1004
1005 The following class is an example of a generic serializer that can handle coercing arbitrary complex objects into primitive representations.
1006
1007 class ObjectSerializer(serializers.BaseSerializer):
1008 """
1009 A read-only serializer that coerces arbitrary complex objects
1010 into primitive representations.
1011 """
1012 def to_representation(self, instance):
1013 output = {}
1014 for attribute_name in dir(instance):
1015 attribute = getattr(instance, attribute_name)
1016 if attribute_name.startswith('_'):
1017 # Ignore private attributes.
1018 pass
1019 elif hasattr(attribute, '__call__'):
1020 # Ignore methods and other callables.
1021 pass
1022 elif isinstance(attribute, (str, int, bool, float, type(None))):
1023 # Primitive types can be passed through unmodified.
1024 output[attribute_name] = attribute
1025 elif isinstance(attribute, list):
1026 # Recursively deal with items in lists.
1027 output[attribute_name] = [
1028 self.to_representation(item) for item in attribute
1029 ]
1030 elif isinstance(attribute, dict):
1031 # Recursively deal with items in dictionaries.
1032 output[attribute_name] = {
1033 str(key): self.to_representation(value)
1034 for key, value in attribute.items()
1035 }
1036 else:
1037 # Force anything else to its string representation.
1038 output[attribute_name] = str(attribute)
1039 return output
1040
1041 ---
1042
1043 ## Advanced serializer usage
1044
1045 ### Overriding serialization and deserialization behavior
1046
1047 If you need to alter the serialization or deserialization behavior of a serializer class, you can do so by overriding the `.to_representation()` or `.to_internal_value()` methods.
1048
1049 Some reasons this might be useful include...
1050
1051 * Adding new behavior for new serializer base classes.
1052 * Modifying the behavior slightly for an existing class.
1053 * Improving serialization performance for a frequently accessed API endpoint that returns lots of data.
1054
1055 The signatures for these methods are as follows:
1056
1057 #### `to_representation(self, instance)`
1058
1059 Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API.
1060
1061 May be overridden in order to modify the representation style. For example:
1062
1063 def to_representation(self, instance):
1064 """Convert `username` to lowercase."""
1065 ret = super().to_representation(instance)
1066 ret['username'] = ret['username'].lower()
1067 return ret
1068
1069 #### ``to_internal_value(self, data)``
1070
1071 Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class.
1072
1073 If any of the validation fails, then the method should raise a `serializers.ValidationError(errors)`. The `errors` argument should be a dictionary mapping field names (or `settings.NON_FIELD_ERRORS_KEY`) to a list of error messages. If you don't need to alter deserialization behavior and instead want to provide object-level validation, it's recommended that you instead override the [`.validate()`](#object-level-validation) method.
1074
1075 The `data` argument passed to this method will normally be the value of `request.data`, so the datatype it provides will depend on the parser classes you have configured for your API.
1076
1077 ### Serializer Inheritance
1078
1079 Similar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example,
1080
1081 class MyBaseSerializer(Serializer):
1082 my_field = serializers.CharField()
1083
1084 def validate_my_field(self, value):
1085 ...
1086
1087 class MySerializer(MyBaseSerializer):
1088 ...
1089
1090 Like Django's `Model` and `ModelForm` classes, the inner `Meta` class on serializers does not implicitly inherit from it's parents' inner `Meta` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example:
1091
1092 class AccountSerializer(MyBaseSerializer):
1093 class Meta(MyBaseSerializer.Meta):
1094 model = Account
1095
1096 Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly.
1097
1098 Additionally, the following caveats apply to serializer inheritance:
1099
1100 * Normal Python name resolution rules apply. If you have multiple base classes that declare a `Meta` inner class, only the first one will be used. This means the child’s `Meta`, if it exists, otherwise the `Meta` of the first parent, etc.
1101 * It’s possible to declaratively remove a `Field` inherited from a parent class by setting the name to be `None` on the subclass.
1102
1103 class MyBaseSerializer(ModelSerializer):
1104 my_field = serializers.CharField()
1105
1106 class MySerializer(MyBaseSerializer):
1107 my_field = None
1108
1109 However, you can only use this technique to opt out from a field defined declaratively by a parent class; it won’t prevent the `ModelSerializer` from generating a default field. To opt-out from default fields, see [Specifying which fields to include](#specifying-which-fields-to-include).
1110
1111 ### Dynamically modifying fields
1112
1113 Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the `.fields` attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer.
1114
1115 Modifying the `fields` argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer.
1116
1117 #### Example
1118
1119 For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so:
1120
1121 class DynamicFieldsModelSerializer(serializers.ModelSerializer):
1122 """
1123 A ModelSerializer that takes an additional `fields` argument that
1124 controls which fields should be displayed.
1125 """
1126
1127 def __init__(self, *args, **kwargs):
1128 # Don't pass the 'fields' arg up to the superclass
1129 fields = kwargs.pop('fields', None)
1130
1131 # Instantiate the superclass normally
1132 super().__init__(*args, **kwargs)
1133
1134 if fields is not None:
1135 # Drop any fields that are not specified in the `fields` argument.
1136 allowed = set(fields)
1137 existing = set(self.fields)
1138 for field_name in existing - allowed:
1139 self.fields.pop(field_name)
1140
1141 This would then allow you to do the following:
1142
1143 >>> class UserSerializer(DynamicFieldsModelSerializer):
1144 >>> class Meta:
1145 >>> model = User
1146 >>> fields = ['id', 'username', 'email']
1147 >>>
1148 >>> print(UserSerializer(user))
1149 {'id': 2, 'username': 'jonwatts', 'email': '[email protected]'}
1150 >>>
1151 >>> print(UserSerializer(user, fields=('id', 'email')))
1152 {'id': 2, 'email': '[email protected]'}
1153
1154 ### Customizing the default fields
1155
1156 REST framework 2 provided an API to allow developers to override how a `ModelSerializer` class would automatically generate the default set of fields.
1157
1158 This API included the `.get_field()`, `.get_pk_field()` and other methods.
1159
1160 Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change.
1161
1162 ---
1163
1164 ## Third party packages
1165
1166 The following third party packages are also available.
1167
1168 ### Django REST marshmallow
1169
1170 The [django-rest-marshmallow][django-rest-marshmallow] package provides an alternative implementation for serializers, using the python [marshmallow][marshmallow] library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases.
1171
1172 ### Serpy
1173
1174 The [serpy][serpy] package is an alternative implementation for serializers that is built for speed. [Serpy][serpy] serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed.
1175
1176 ### MongoengineModelSerializer
1177
1178 The [django-rest-framework-mongoengine][mongoengine] package provides a `MongoEngineModelSerializer` serializer class that supports using MongoDB as the storage layer for Django REST framework.
1179
1180 ### GeoFeatureModelSerializer
1181
1182 The [django-rest-framework-gis][django-rest-framework-gis] package provides a `GeoFeatureModelSerializer` serializer class that supports GeoJSON both for read and write operations.
1183
1184 ### HStoreSerializer
1185
1186 The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreSerializer` to support [django-hstore][django-hstore] `DictionaryField` model field and its `schema-mode` feature.
1187
1188 ### Dynamic REST
1189
1190 The [dynamic-rest][dynamic-rest] package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers.
1191
1192 ### Dynamic Fields Mixin
1193
1194 The [drf-dynamic-fields][drf-dynamic-fields] package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter.
1195
1196 ### DRF FlexFields
1197
1198 The [drf-flex-fields][drf-flex-fields] package extends the ModelSerializer and ModelViewSet to provide commonly used functionality for dynamically setting fields and expanding primitive fields to nested models, both from URL parameters and your serializer class definitions.
1199
1200 ### Serializer Extensions
1201
1202 The [django-rest-framework-serializer-extensions][drf-serializer-extensions]
1203 package provides a collection of tools to DRY up your serializers, by allowing
1204 fields to be defined on a per-view/request basis. Fields can be whitelisted,
1205 blacklisted and child serializers can be optionally expanded.
1206
1207 ### HTML JSON Forms
1208
1209 The [html-json-forms][html-json-forms] package provides an algorithm and serializer for processing `<form>` submissions per the (inactive) [HTML JSON Form specification][json-form-spec]. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, `<input name="items[0][id]" value="5">` will be interpreted as `{"items": [{"id": "5"}]}`.
1210
1211 ### DRF-Base64
1212
1213 [DRF-Base64][drf-base64] provides a set of field and model serializers that handles the upload of base64-encoded files.
1214
1215 ### QueryFields
1216
1217 [djangorestframework-queryfields][djangorestframework-queryfields] allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters.
1218
1219 ### DRF Writable Nested
1220
1221 The [drf-writable-nested][drf-writable-nested] package provides writable nested model serializer which allows to create/update models with nested related data.
1222
1223 ### DRF Encrypt Content
1224
1225 The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
1226
1227 ### Shapeless Serializers
1228
1229 The [drf-shapeless-serializers][drf-shapeless-serializers] package provides dynamic serializer configuration capabilities, allowing runtime field selection, renaming, attribute modification, and nested relationship configuration without creating multiple serializer classes. It helps eliminate serializer boilerplate while providing flexible API responses.
1230
1231 ### DRF Pydantic
1232
1233 The [drf-pydantic][drf-pydantic] package allows you to use Pydantic with Django REST framework for data validation and (de)serialization. If you develop DRF APIs and rely on Pydantic for data validation, this package provides seamless integration between both libraries.
1234
1235
1236 [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
1237 [relations]: relations.md
1238 [model-managers]: https://docs.djangoproject.com/en/stable/topics/db/managers/
1239 [encapsulation-blogpost]: https://www.dabapps.com/blog/django-models-and-encapsulation/
1240 [thirdparty-writable-nested]: serializers.md#drf-writable-nested
1241 [django-rest-marshmallow]: https://marshmallow-code.github.io/django-rest-marshmallow/
1242 [marshmallow]: https://marshmallow.readthedocs.io/en/latest/
1243 [serpy]: https://github.com/clarkduvall/serpy
1244 [mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine
1245 [django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis
1246 [django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
1247 [django-hstore]: https://github.com/djangonauts/django-hstore
1248 [dynamic-rest]: https://github.com/AltSchool/dynamic-rest
1249 [html-json-forms]: https://github.com/wq/html-json-forms
1250 [drf-flex-fields]: https://github.com/rsinger86/drf-flex-fields
1251 [json-form-spec]: https://www.w3.org/TR/html-json-forms/
1252 [drf-dynamic-fields]: https://github.com/dbrgn/drf-dynamic-fields
1253 [drf-base64]: https://bitbucket.org/levit_scs/drf_base64
1254 [drf-serializer-extensions]: https://github.com/evenicoulddoit/django-rest-framework-serializer-extensions
1255 [djangorestframework-queryfields]: https://djangorestframework-queryfields.readthedocs.io/
1256 [drf-writable-nested]: https://github.com/beda-software/drf-writable-nested
1257 [drf-encrypt-content]: https://github.com/oguzhancelikarslan/drf-encrypt-content
1258 [drf-shapeless-serializers]: https://github.com/khaledsukkar2/drf-shapeless-serializers
1259 [drf-pydantic]: https://github.com/georgebv/drf-pydantic