Debian Codegraph @

docs/community/3.0-announcement.md

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # Django REST framework 3.0
2
3 The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views.
4
5 **This release is incremental in nature. There *are* some breaking API changes, and upgrading *will* require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.**
6
7 The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier.
8
9 3.0 is the first of three releases that have been funded by our recent [Kickstarter campaign][kickstarter].
10
11 As ever, a huge thank you to our many [wonderful sponsors][sponsors]. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring.
12
13 ---
14
15 ## New features
16
17 Notable features of this new release include:
18
19 * Printable representations on serializers that allow you to inspect exactly what fields are present on the instance.
20 * Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit `ModelSerializer` class and the explicit `Serializer` class.
21 * A new `BaseSerializer` class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic.
22 * A cleaner fields API including new classes such as `ListField` and `MultipleChoiceField`.
23 * [Super simple default implementations][mixins.py] for the generic views.
24 * Support for overriding how validation errors are handled by your API.
25 * A metadata API that allows you to customize how `OPTIONS` requests are handled by your API.
26 * A more compact JSON output with unicode style encoding turned on by default.
27 * Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release.
28
29 Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release.
30
31 ---
32
33 #### REST framework: Under the hood.
34
35 This talk from the [Django: Under the Hood](https://www.djangounderthehood.com/) event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.
36
37 <iframe style="display: block; margin: 0 auto 0 auto" width="560" height="315" src="//www.youtube.com/embed/3cSsbe-tA0E" frameborder="0" allowfullscreen></iframe>
38
39 ---
40
41 *Below is an in-depth guide to the API changes and migration notes for 3.0.*
42
43 ## Request objects
44
45 #### The `.data` and `.query_params` properties.
46
47 The usage of `request.DATA` and `request.FILES` is now pending deprecation in favor of a single `request.data` attribute that contains *all* the parsed data.
48
49 Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports.
50
51 You may now pass all the request data to a serializer class in a single argument:
52
53 # Do this...
54 ExampleSerializer(data=request.data)
55
56 Instead of passing the files argument separately:
57
58 # Don't do this...
59 ExampleSerializer(data=request.DATA, files=request.FILES)
60
61
62 The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the lowercased `request.query_params`.
63
64 ---
65
66 ## Serializers
67
68 #### Single-step object creation.
69
70 Previously the serializers used a two-step object creation, as follows:
71
72 1. Validating the data would create an object instance. This instance would be available as `serializer.object`.
73 2. Calling `serializer.save()` would then save the object instance to the database.
74
75 This style is in-line with how the `ModelForm` class works in Django, but is problematic for a number of reasons:
76
77 * Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called.
78 * Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints.
79 * The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save?
80
81 We now use single-step object creation, like so:
82
83 1. Validating the data makes the cleaned data available as `serializer.validated_data`.
84 2. Calling `serializer.save()` then saves and returns the new object instance.
85
86 The resulting API changes are further detailed below.
87
88 #### The `.create()` and `.update()` methods.
89
90 The `.restore_object()` method is now removed, and we instead have two separate methods, `.create()` and `.update()`. These methods work slightly different to the previous `.restore_object()`.
91
92 When using the `.create()` and `.update()` methods you should both create *and save* the object instance. This is in contrast to the previous `.restore_object()` behavior that would instantiate the object but not save it.
93
94 These methods also replace the optional `.save_object()` method, which no longer exists.
95
96 The following example from the tutorial previously used `restore_object()` to handle both creating and updating object instances.
97
98 def restore_object(self, attrs, instance=None):
99 if instance:
100 # Update existing instance
101 instance.title = attrs.get('title', instance.title)
102 instance.code = attrs.get('code', instance.code)
103 instance.linenos = attrs.get('linenos', instance.linenos)
104 instance.language = attrs.get('language', instance.language)
105 instance.style = attrs.get('style', instance.style)
106 return instance
107
108 # Create new instance
109 return Snippet(**attrs)
110
111 This would now be split out into two separate methods.
112
113 def update(self, instance, validated_data):
114 instance.title = validated_data.get('title', instance.title)
115 instance.code = validated_data.get('code', instance.code)
116 instance.linenos = validated_data.get('linenos', instance.linenos)
117 instance.language = validated_data.get('language', instance.language)
118 instance.style = validated_data.get('style', instance.style)
119 instance.save()
120 return instance
121
122 def create(self, validated_data):
123 return Snippet.objects.create(**validated_data)
124
125 Note that these methods should return the newly created object instance.
126
127 #### Use `.validated_data` instead of `.object`.
128
129 You must now use the `.validated_data` attribute if you need to inspect the data before saving, rather than using the `.object` attribute, which no longer exists.
130
131 For example the following code *is no longer valid*:
132
133 if serializer.is_valid():
134 name = serializer.object.name # Inspect validated field data.
135 logging.info('Creating ticket "%s"' % name)
136 serializer.object.user = request.user # Include the user when saving.
137 serializer.save()
138
139 Instead of using `.object` to inspect a partially constructed instance, you would now use `.validated_data` to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the `.save()` method as keyword arguments.
140
141 The corresponding code would now look like this:
142
143 if serializer.is_valid():
144 name = serializer.validated_data['name'] # Inspect validated field data.
145 logging.info('Creating ticket "%s"' % name)
146 serializer.save(user=request.user) # Include the user when saving.
147
148 #### Using `.is_valid(raise_exception=True)`
149
150 The `.is_valid()` method now takes an optional boolean flag, `raise_exception`.
151
152 Calling `.is_valid(raise_exception=True)` will cause a `ValidationError` to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code.
153
154 The handling and formatting of error responses may be altered globally by using the `EXCEPTION_HANDLER` settings key.
155
156 This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides.
157
158 #### Using `serializers.ValidationError`.
159
160 Previously `serializers.ValidationError` error was simply a synonym for `django.core.exceptions.ValidationError`. This has now been altered so that it inherits from the standard `APIException` base class.
161
162 The reason behind this is that Django's `ValidationError` class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers.
163
164 For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the `serializers.ValidationError` exception class, and not Django's built-in exception.
165
166 We strongly recommend that you use the namespaced import style of `import serializers` and not `from serializers import ValidationError` in order to avoid any potential confusion.
167
168 #### Change to `validate_<field_name>`.
169
170 The `validate_<field_name>` method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field:
171
172 def validate_score(self, attrs, source):
173 if attrs['score'] % 10 != 0:
174 raise serializers.ValidationError('This field should be a multiple of ten.')
175 return attrs
176
177 This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.
178
179 def validate_score(self, value):
180 if value % 10 != 0:
181 raise serializers.ValidationError('This field should be a multiple of ten.')
182 return value
183
184 Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual.
185
186 Because `.validate_<field_name>` would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use `.validate()` instead.
187
188 You can either return `non_field_errors` from the validate method by raising a simple `ValidationError`
189
190 def validate(self, attrs):
191 # serializer.errors == {'non_field_errors': ['A non field error']}
192 raise serializers.ValidationError('A non field error')
193
194 Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the `ValidationError`, like so:
195
196 def validate(self, attrs):
197 # serializer.errors == {'my_field': ['A field error']}
198 raise serializers.ValidationError({'my_field': 'A field error'})
199
200 This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.
201
202 #### Removal of `transform_<field_name>`.
203
204 The under-used `transform_<field_name>` on serializer classes is no longer provided. Instead you should just override `to_representation()` if you need to apply any modifications to the representation style.
205
206 For example:
207
208 def to_representation(self, instance):
209 ret = super(UserSerializer, self).to_representation(instance)
210 ret['username'] = ret['username'].lower()
211 return ret
212
213 Dropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches.
214
215 If you absolutely need to preserve `transform_<field_name>` behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example:
216
217 class BaseModelSerializer(ModelSerializer):
218 """
219 A custom ModelSerializer class that preserves 2.x style `transform_<field_name>` behavior.
220 """
221 def to_representation(self, instance):
222 ret = super(BaseModelSerializer, self).to_representation(instance)
223 for key, value in ret.items():
224 method = getattr(self, 'transform_' + key, None)
225 if method is not None:
226 ret[key] = method(value)
227 return ret
228
229 #### Differences between ModelSerializer validation and ModelForm.
230
231 This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes.
232
233 For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different.
234
235 The one difference that you do need to note is that the `.clean()` method will not be called as part of serializer validation, as it would be if using a `ModelForm`. Use the serializer `.validate()` method to perform a final validation step on incoming data where required.
236
237 There may be some cases where you really do need to keep validation logic in the model `.clean()` method, and cannot instead separate it into the serializer `.validate()`. You can do so by explicitly instantiating a model instance in the `.validate()` method.
238
239 def validate(self, attrs):
240 instance = ExampleModel(**attrs)
241 instance.clean()
242 return attrs
243
244 Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path.
245
246 #### Writable nested serialization.
247
248 REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic:
249
250 * There can be complex dependencies involved in order of saving multiple related model instances.
251 * It's unclear what behavior the user should expect when related models are passed `None` data.
252 * It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.
253
254 Using the `depth` option on `ModelSerializer` will now create **read-only nested serializers** by default.
255
256 If you try to use a writable nested serializer without writing a custom `create()` and/or `update()` method you'll see an assertion error when you attempt to save the serializer. For example:
257
258 >>> class ProfileSerializer(serializers.ModelSerializer):
259 >>> class Meta:
260 >>> model = Profile
261 >>> fields = ['address', 'phone']
262 >>>
263 >>> class UserSerializer(serializers.ModelSerializer):
264 >>> profile = ProfileSerializer()
265 >>> class Meta:
266 >>> model = User
267 >>> fields = ['username', 'email', 'profile']
268 >>>
269 >>> data = {
270 >>> 'username': 'lizzy',
271 >>> 'email': '[email protected]',
272 >>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}
273 >>> }
274 >>>
275 >>> serializer = UserSerializer(data=data)
276 >>> serializer.save()
277 AssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields.
278
279 To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the `create()` and/or `update()` methods explicitly.
280
281 class UserSerializer(serializers.ModelSerializer):
282 profile = ProfileSerializer()
283
284 class Meta:
285 model = User
286 fields = ['username', 'email', 'profile']
287
288 def create(self, validated_data):
289 profile_data = validated_data.pop('profile')
290 user = User.objects.create(**validated_data)
291 Profile.objects.create(user=user, **profile_data)
292 return user
293
294 The single-step object creation makes this far simpler and more obvious than the previous `.restore_object()` behavior.
295
296 #### Printable serializer representations.
297
298 Serializer instances now support a printable representation that allows you to inspect the fields present on the instance.
299
300 For instance, given the following example model:
301
302 class LocationRating(models.Model):
303 location = models.CharField(max_length=100)
304 rating = models.IntegerField()
305 created_by = models.ForeignKey(User)
306
307 Let's create a simple `ModelSerializer` class corresponding to the `LocationRating` model.
308
309 class LocationRatingSerializer(serializer.ModelSerializer):
310 class Meta:
311 model = LocationRating
312
313 We can now inspect the serializer representation in the Django shell, using `python manage.py shell`...
314
315 >>> serializer = LocationRatingSerializer()
316 >>> print(serializer) # Or use `print serializer` in Python 2.x
317 LocationRatingSerializer():
318 id = IntegerField(label='ID', read_only=True)
319 location = CharField(max_length=100)
320 rating = IntegerField()
321 created_by = PrimaryKeyRelatedField(queryset=User.objects.all())
322
323 #### The `extra_kwargs` option.
324
325 The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDeprecation` and replaced with a more generic `extra_kwargs`.
326
327 class MySerializer(serializer.ModelSerializer):
328 class Meta:
329 model = MyModel
330 fields = ['id', 'email', 'notes', 'is_admin']
331 extra_kwargs = {
332 'is_admin': {'write_only': True}
333 }
334
335 Alternatively, specify the field explicitly on the serializer class:
336
337 class MySerializer(serializer.ModelSerializer):
338 is_admin = serializers.BooleanField(write_only=True)
339
340 class Meta:
341 model = MyModel
342 fields = ['id', 'email', 'notes', 'is_admin']
343
344 The `read_only_fields` option remains as a convenient shortcut for the more common case.
345
346 #### Changes to `HyperlinkedModelSerializer`.
347
348 The `view_name` and `lookup_field` options have been moved to `PendingDeprecation`. They are no longer required, as you can use the `extra_kwargs` argument instead:
349
350 class MySerializer(serializer.HyperlinkedModelSerializer):
351 class Meta:
352 model = MyModel
353 fields = ['url', 'email', 'notes', 'is_admin']
354 extra_kwargs = {
355 'url': {'lookup_field': 'uuid'}
356 }
357
358 Alternatively, specify the field explicitly on the serializer class:
359
360 class MySerializer(serializer.HyperlinkedModelSerializer):
361 url = serializers.HyperlinkedIdentityField(
362 view_name='mymodel-detail',
363 lookup_field='uuid'
364 )
365
366 class Meta:
367 model = MyModel
368 fields = ['url', 'email', 'notes', 'is_admin']
369
370 #### Fields for model methods and properties.
371
372 With `ModelSerializer` you can now specify field names in the `fields` option that refer to model methods or properties. For example, suppose you have the following model:
373
374 class Invitation(models.Model):
375 created = models.DateTimeField()
376 to_email = models.EmailField()
377 message = models.CharField(max_length=1000)
378
379 def expiry_date(self):
380 return self.created + datetime.timedelta(days=30)
381
382 You can include `expiry_date` as a field option on a `ModelSerializer` class.
383
384 class InvitationSerializer(serializers.ModelSerializer):
385 class Meta:
386 model = Invitation
387 fields = ['to_email', 'message', 'expiry_date']
388
389 These fields will be mapped to `serializers.ReadOnlyField()` instances.
390
391 >>> serializer = InvitationSerializer()
392 >>> print(repr(serializer))
393 InvitationSerializer():
394 to_email = EmailField(max_length=75)
395 message = CharField(max_length=1000)
396 expiry_date = ReadOnlyField()
397
398 #### The `ListSerializer` class.
399
400 The `ListSerializer` class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.
401
402 class MultipleUserSerializer(ListSerializer):
403 child = UserSerializer()
404
405 You can also still use the `many=True` argument to serializer classes. It's worth noting that `many=True` argument transparently creates a `ListSerializer` instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase.
406
407 You will typically want to *continue to use the existing `many=True` flag* rather than declaring `ListSerializer` classes explicitly, but declaring the classes explicitly can be useful if you need to write custom `create` or `update` methods for bulk updates, or provide for other custom behavior.
408
409 See also the new `ListField` class, which validates input in the same way, but does not include the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on.
410
411 #### The `BaseSerializer` class.
412
413 REST framework now includes a simple `BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles.
414
415 This class implements the same basic API as the `Serializer` class:
416
417 * `.data` - Returns the outgoing primitive representation.
418 * `.is_valid()` - Deserializes and validates incoming data.
419 * `.validated_data` - Returns the validated incoming data.
420 * `.errors` - Returns an errors during validation.
421 * `.save()` - Persists the validated data into an object instance.
422
423 There are four methods that can be overridden, depending on what functionality you want the serializer class to support:
424
425 * `.to_representation()` - Override this to support serialization, for read operations.
426 * `.to_internal_value()` - Override this to support deserialization, for write operations.
427 * `.create()` and `.update()` - Override either or both of these to support saving instances.
428
429 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`.
430
431 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.
432
433 ##### Read-only `BaseSerializer` classes.
434
435 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:
436
437 class HighScore(models.Model):
438 created = models.DateTimeField(auto_now_add=True)
439 player_name = models.CharField(max_length=10)
440 score = models.IntegerField()
441
442 It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types.
443
444 class HighScoreSerializer(serializers.BaseSerializer):
445 def to_representation(self, obj):
446 return {
447 'score': obj.score,
448 'player_name': obj.player_name
449 }
450
451 We can now use this class to serialize single `HighScore` instances:
452
453 @api_view(['GET'])
454 def high_score(request, pk):
455 instance = HighScore.objects.get(pk=pk)
456 serializer = HighScoreSerializer(instance)
457 return Response(serializer.data)
458
459 Or use it to serialize multiple instances:
460
461 @api_view(['GET'])
462 def all_high_scores(request):
463 queryset = HighScore.objects.order_by('-score')
464 serializer = HighScoreSerializer(queryset, many=True)
465 return Response(serializer.data)
466
467 ##### Read-write `BaseSerializer` classes.
468
469 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 `ValidationError` if the supplied data is in an incorrect format.
470
471 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`.
472
473 If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods.
474
475 Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations.
476
477 class HighScoreSerializer(serializers.BaseSerializer):
478 def to_internal_value(self, data):
479 score = data.get('score')
480 player_name = data.get('player_name')
481
482 # Perform the data validation.
483 if not score:
484 raise ValidationError({
485 'score': 'This field is required.'
486 })
487 if not player_name:
488 raise ValidationError({
489 'player_name': 'This field is required.'
490 })
491 if len(player_name) > 10:
492 raise ValidationError({
493 'player_name': 'May not be more than 10 characters.'
494 })
495
496 # Return the validated values. This will be available as
497 # the `.validated_data` property.
498 return {
499 'score': int(score),
500 'player_name': player_name
501 }
502
503 def to_representation(self, obj):
504 return {
505 'score': obj.score,
506 'player_name': obj.player_name
507 }
508
509 def create(self, validated_data):
510 return HighScore.objects.create(**validated_data)
511
512 #### Creating new generic serializers with `BaseSerializer`.
513
514 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.
515
516 The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
517
518 class ObjectSerializer(serializers.BaseSerializer):
519 """
520 A read-only serializer that coerces arbitrary complex objects
521 into primitive representations.
522 """
523 def to_representation(self, obj):
524 for attribute_name in dir(obj):
525 attribute = getattr(obj, attribute_name)
526 if attribute_name.startswith('_'):
527 # Ignore private attributes.
528 pass
529 elif hasattr(attribute, '__call__'):
530 # Ignore methods and other callables.
531 pass
532 elif isinstance(attribute, (str, int, bool, float, type(None))):
533 # Primitive types can be passed through unmodified.
534 output[attribute_name] = attribute
535 elif isinstance(attribute, list):
536 # Recursively deal with items in lists.
537 output[attribute_name] = [
538 self.to_representation(item) for item in attribute
539 ]
540 elif isinstance(attribute, dict):
541 # Recursively deal with items in dictionaries.
542 output[attribute_name] = {
543 str(key): self.to_representation(value)
544 for key, value in attribute.items()
545 }
546 else:
547 # Force anything else to its string representation.
548 output[attribute_name] = str(attribute)
549
550 ---
551
552 ## Serializer fields
553
554 #### The `Field` and `ReadOnly` field classes.
555
556 There are some minor tweaks to the field base classes.
557
558 Previously we had these two base classes:
559
560 * `Field` as the base class for read-only fields. A default implementation was included for serializing data.
561 * `WritableField` as the base class for read-write fields.
562
563 We now use the following:
564
565 * `Field` is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.
566 * `ReadOnlyField` is a concrete implementation for read-only fields that simply returns the attribute value without modification.
567
568 #### The `required`, `allow_null`, `allow_blank` and `default` arguments.
569
570 REST framework now has more explicit and clear control over validating empty values for fields.
571
572 Previously the meaning of the `required=False` keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be `None` or the empty string.
573
574 We now have a better separation, with separate `required`, `allow_null` and `allow_blank` arguments.
575
576 The following set of arguments are used to control validation of empty values:
577
578 * `required=False`: The value does not need to be present in the input, and will not be passed to `.create()` or `.update()` if it is not seen.
579 * `default=<value>`: The value does not need to be present in the input, and a default value will be passed to `.create()` or `.update()` if it is not seen.
580 * `allow_null=True`: `None` is a valid input.
581 * `allow_blank=True`: `''` is valid input. For `CharField` and subclasses only.
582
583 Typically you'll want to use `required=False` if the corresponding model field has a default value, and additionally set either `allow_null=True` or `allow_blank=True` if required.
584
585 The `default` argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the `required` argument when a default is specified, and doing so will result in an error.
586
587 #### Coercing output types.
588
589 The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an `IntegerField` would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior.
590
591 #### Removal of `.validate()`.
592
593 The `.validate()` method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override `to_internal_value()`.
594
595 class UppercaseCharField(serializers.CharField):
596 def to_internal_value(self, data):
597 value = super(UppercaseCharField, self).to_internal_value(data)
598 if value != value.upper():
599 raise serializers.ValidationError('The input should be uppercase only.')
600 return value
601
602 Previously validation errors could be raised in either `.to_native()` or `.validate()`, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.
603
604 #### The `ListField` class.
605
606 The `ListField` class has now been added. This field validates list input. It takes a `child` keyword argument which is used to specify the field used to validate each item in the list. For example:
607
608 scores = ListField(child=IntegerField(min_value=0, max_value=100))
609
610 You can also use a declarative style to create new subclasses of `ListField`, like this:
611
612 class ScoresField(ListField):
613 child = IntegerField(min_value=0, max_value=100)
614
615 We can now use the `ScoresField` class inside another serializer:
616
617 scores = ScoresField()
618
619 See also the new `ListSerializer` class, which validates input in the same way, but also includes the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on.
620
621 #### The `ChoiceField` class may now accept a flat list.
622
623 The `ChoiceField` class may now accept a list of choices in addition to the existing style of using a list of pairs of `(name, display_value)`. The following is now valid:
624
625 color = ChoiceField(choices=['red', 'green', 'blue'])
626
627 #### The `MultipleChoiceField` class.
628
629 The `MultipleChoiceField` class has been added. This field acts like `ChoiceField`, but returns a set, which may include none, one or many of the valid choices.
630
631 #### Changes to the custom field API.
632
633 The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`.
634
635 The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customize the behavior in a way that did not simply lookup the field value from the object. For example...
636
637 def field_to_native(self, obj, field_name):
638 """A custom read-only field that returns the class name."""
639 return obj.__class__.__name__
640
641 Now if you need to access the entire object you'll instead need to override one or both of the following:
642
643 * Use `get_attribute` to modify the attribute value passed to `to_representation()`.
644 * Use `get_value` to modify the data value passed `to_internal_value()`.
645
646 For example:
647
648 def get_attribute(self, obj):
649 # Pass the entire object through to `to_representation()`,
650 # instead of the standard attribute lookup.
651 return obj
652
653 def to_representation(self, value):
654 return value.__class__.__name__
655
656 #### Explicit `queryset` required on relational fields.
657
658 Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a `ModelSerializer`.
659
660 This code *would be valid* in `2.4.3`:
661
662 class AccountSerializer(serializers.ModelSerializer):
663 organizations = serializers.SlugRelatedField(slug_field='name')
664
665 class Meta:
666 model = Account
667
668 However this code *would not be valid* in `3.0`:
669
670 # Missing `queryset`
671 class AccountSerializer(serializers.Serializer):
672 organizations = serializers.SlugRelatedField(slug_field='name')
673
674 def restore_object(self, attrs, instance=None):
675 # ...
676
677 The queryset argument is now always required for writable relational fields.
678 This removes some magic and makes it easier and more obvious to move between implicit `ModelSerializer` classes and explicit `Serializer` classes.
679
680 class AccountSerializer(serializers.ModelSerializer):
681 organizations = serializers.SlugRelatedField(
682 slug_field='name',
683 queryset=Organization.objects.all()
684 )
685
686 class Meta:
687 model = Account
688
689 The `queryset` argument is only ever required for writable fields, and is not required or valid for fields with `read_only=True`.
690
691 #### Optional argument to `SerializerMethodField`.
692
693 The argument to `SerializerMethodField` is now optional, and defaults to `get_<field_name>`. For example the following is valid:
694
695 class AccountSerializer(serializers.Serializer):
696 # `method_name='get_billing_details'` by default.
697 billing_details = serializers.SerializerMethodField()
698
699 def get_billing_details(self, account):
700 return calculate_billing(account)
701
702 In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code *will raise an error*:
703
704 billing_details = serializers.SerializerMethodField('get_billing_details')
705
706 #### Enforcing consistent `source` usage.
707
708 I've see several codebases that unnecessarily include the `source` argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that `source` is usually not required.
709
710 The following usage will *now raise an error*:
711
712 email = serializers.EmailField(source='email')
713
714 #### The `UniqueValidator` and `UniqueTogetherValidator` classes.
715
716 REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit `Serializer` class instead of using `ModelSerializer`.
717
718 The `UniqueValidator` should be applied to a serializer field, and takes a single `queryset` argument.
719
720 from rest_framework import serializers
721 from rest_framework.validators import UniqueValidator
722
723 class OrganizationSerializer(serializers.Serializer):
724 url = serializers.HyperlinkedIdentityField(view_name='organization_detail')
725 created = serializers.DateTimeField(read_only=True)
726 name = serializers.CharField(
727 max_length=100,
728 validators=UniqueValidator(queryset=Organization.objects.all())
729 )
730
731 The `UniqueTogetherValidator` should be applied to a serializer, and takes a `queryset` argument and a `fields` argument which should be a list or tuple of field names.
732
733 class RaceResultSerializer(serializers.Serializer):
734 category = serializers.ChoiceField(['5k', '10k'])
735 position = serializers.IntegerField()
736 name = serializers.CharField(max_length=100)
737
738 class Meta:
739 validators = [UniqueTogetherValidator(
740 queryset=RaceResult.objects.all(),
741 fields=['category', 'position']
742 )]
743
744 #### The `UniqueForDateValidator` classes.
745
746 REST framework also now includes explicit validator classes for validating the `unique_for_date`, `unique_for_month`, and `unique_for_year` model field constraints. These are used internally instead of calling into `Model.full_clean()`.
747
748 These classes are documented in the [Validators](../api-guide/validators.md) section of the documentation.
749
750 ---
751
752 ## Generic views
753
754 #### Simplification of view logic.
755
756 The view logic for the default method handlers has been significantly simplified, due to the new serializers API.
757
758 #### Changes to pre/post save hooks.
759
760 The `pre_save` and `post_save` hooks no longer exist, but are replaced with `perform_create(self, serializer)` and `perform_update(self, serializer)`.
761
762 These methods should save the object instance by calling `serializer.save()`, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.
763
764 For example:
765
766 def perform_create(self, serializer):
767 # Include the owner attribute directly, rather than from request data.
768 instance = serializer.save(owner=self.request.user)
769 # Perform a custom post-save action.
770 send_email(instance.to_email, instance.message)
771
772 The `pre_delete` and `post_delete` hooks no longer exist, and are replaced with `.perform_destroy(self, instance)`, which should delete the instance and perform any custom actions.
773
774 def perform_destroy(self, instance):
775 # Perform a custom pre-delete action.
776 send_deletion_alert(user=instance.created_by, deleted=instance)
777 # Delete the object instance.
778 instance.delete()
779
780 #### Removal of view attributes.
781
782 The `.object` and `.object_list` attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic.
783
784 I would personally recommend that developers treat view instances as immutable objects in their application code.
785
786 #### PUT as create.
787
788 Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses.
789
790 Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.
791
792 If you need to restore the previous behavior you may want to include [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views.
793
794 #### Customizing error responses.
795
796 The generic views now raise `ValidationFailed` exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a `400 Bad Request` response directly.
797
798 This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.
799
800 ---
801
802 ## The metadata API
803
804 Behavior for dealing with `OPTIONS` requests was previously built directly into the class-based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.
805
806 This makes it far easier to use a different style for `OPTIONS` responses throughout your API, and makes it possible to create third-party metadata policies.
807
808 ---
809
810 ## Serializers as HTML forms
811
812 REST framework 3.0 includes templated HTML form rendering for serializers.
813
814 This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.
815
816 Significant changes that you do need to be aware of include:
817
818 * Nested HTML forms are now supported, for example, a `UserSerializer` with a nested `ProfileSerializer` will now render a nested `fieldset` when used in the browsable API.
819 * Nested lists of HTML forms are not yet supported, but are planned for 3.1.
820 * Because we now use templated HTML form generation, **the `widget` option is no longer available for serializer fields**. You can instead control the template that is used for a given field, by using the `style` dictionary.
821
822 #### The `style` keyword argument for serializer fields.
823
824 The `style` keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the `HTMLFormRenderer` uses the `base_template` key to determine which template to render the field with.
825
826 For example, to use a `textarea` control instead of the default `input` control, you would use the following…
827
828 additional_notes = serializers.CharField(
829 style={'base_template': 'textarea.html'}
830 )
831
832 Similarly, to use a radio button control instead of the default `select` control, you would use the following…
833
834 color_channel = serializers.ChoiceField(
835 choices=['red', 'blue', 'green'],
836 style={'base_template': 'radio.html'}
837 )
838
839 This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.
840
841 ---
842
843 ## API style
844
845 There are some improvements in the default style we use in our API responses.
846
847 #### Unicode JSON by default.
848
849 Unicode JSON is now the default. The `UnicodeJSONRenderer` class no longer exists, and the `UNICODE_JSON` setting has been added. To revert this behavior use the new setting:
850
851 REST_FRAMEWORK = {
852 'UNICODE_JSON': False
853 }
854
855 #### Compact JSON by default.
856
857 We now output compact JSON in responses by default. For example, we return:
858
859 {"email":"[email protected]","is_admin":true}
860
861 Instead of the following:
862
863 {"email": "[email protected]", "is_admin": true}
864
865 The `COMPACT_JSON` setting has been added, and can be used to revert this behavior if needed:
866
867 REST_FRAMEWORK = {
868 'COMPACT_JSON': False
869 }
870
871 #### File fields as URLs
872
873 The `FileField` and `ImageField` classes are now represented as URLs by default. You should ensure you set Django's [standard `MEDIA_URL` setting](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-MEDIA_URL) appropriately, and ensure your application [serves the uploaded files](https://docs.djangoproject.com/en/stable/howto/static-files/#serving-uploaded-files-in-development).
874
875 You can revert this behavior, and display filenames in the representation by using the `UPLOADED_FILES_USE_URL` settings key:
876
877 REST_FRAMEWORK = {
878 'UPLOADED_FILES_USE_URL': False
879 }
880
881 You can also modify serializer fields individually, using the `use_url` argument:
882
883 uploaded_file = serializers.FileField(use_url=False)
884
885 Also note that you should pass the `request` object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form `https://example.com/url_path/filename.txt`. For example:
886
887 context = {'request': request}
888 serializer = ExampleSerializer(instance, context=context)
889 return Response(serializer.data)
890
891 If the request is omitted from the context, the returned URLs will be of the form `/url_path/filename.txt`.
892
893 #### Throttle headers using `Retry-After`.
894
895 The custom `X-Throttle-Wait-Second` header has now been dropped in favor of the standard `Retry-After` header. You can revert this behavior if needed by writing a custom exception handler for your application.
896
897 #### Date and time objects as ISO-8601 strings in serializer data.
898
899 Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as `Date`, `Time` and `DateTime` objects, and later coerced to strings by the renderer.
900
901 You can modify this behavior globally by settings the existing `DATE_FORMAT`, `DATETIME_FORMAT` and `TIME_FORMAT` settings keys. Setting these values to `None` instead of their default value of `'iso-8601'` will result in native objects being returned in serializer data.
902
903 REST_FRAMEWORK = {
904 # Return native `Date` and `Time` objects in `serializer.data`
905 'DATETIME_FORMAT': None
906 'DATE_FORMAT': None
907 'TIME_FORMAT': None
908 }
909
910 You can also modify serializer fields individually, using the `date_format`, `time_format` and `datetime_format` arguments:
911
912 # Return `DateTime` instances in `serializer.data`, not strings.
913 created = serializers.DateTimeField(format=None)
914
915 #### Decimals as strings in serializer data.
916
917 Decimals are now coerced to strings by default in the serializer output. Previously they were returned as `Decimal` objects, and later coerced to strings by the renderer.
918
919 You can modify this behavior globally by using the `COERCE_DECIMAL_TO_STRING` settings key.
920
921 REST_FRAMEWORK = {
922 'COERCE_DECIMAL_TO_STRING': False
923 }
924
925 Or modify it on an individual serializer field, using the `coerce_to_string` keyword argument.
926
927 # Return `Decimal` instances in `serializer.data`, not strings.
928 amount = serializers.DecimalField(
929 max_digits=10,
930 decimal_places=2,
931 coerce_to_string=False
932 )
933
934 The default JSON renderer will return float objects for un-coerced `Decimal` instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.
935
936 ---
937
938 ## Miscellaneous notes
939
940 * The serializer `ChoiceField` does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.
941 * Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.
942 * Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still [create language files with Django][django-localization] if you wish to localize them.
943 * `APIException` subclasses could previously take any arbitrary type in the `detail` argument. These exceptions now use translatable text strings, and as a result call `force_text` on the `detail` argument, which *must be a string*. If you need complex arguments to an `APIException` class, you should subclass it and override the `__init__()` method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses.
944
945 ---
946
947 ## What's coming next
948
949 3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.
950
951 The 3.1 release is planned to address improvements in the following components:
952
953 * Public API for using serializers as HTML forms.
954 * Request parsing, mediatypes & the implementation of the browsable API.
955 * Introduction of a new pagination API.
956 * Better support for API versioning.
957
958 The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.
959
960 You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/encode/django-rest-framework/milestones).
961
962 [kickstarter]: https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3
963 [sponsors]: https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors
964 [mixins.py]: https://github.com/encode/django-rest-framework/blob/main/rest_framework/mixins.py
965 [django-localization]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#localization-how-to-create-language-files