Debian Codegraph @

docs/community/3.0-announcement.md

raw ◀ ▶
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 <a href="https://www.youtube.com/watch?v=3cSsbe-tA0E">This talk</a> from the [Django: Under the Hood](http://www.djangounderthehood.com/) event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0.
36
37 ---
38
39 *Below is an in-depth guide to the API changes and migration notes for 3.0.*
40
41 ## Request objects
42
43 #### The `.data` and `.query_params` properties.
44
45 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.
46
47 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.
48
49 You may now pass all the request data to a serializer class in a single argument:
50
51 # Do this...
52 ExampleSerializer(data=request.data)
53
54 Instead of passing the files argument separately:
55
56 # Don't do this...
57 ExampleSerializer(data=request.DATA, files=request.FILES)
58
59
60 The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the lowercased `request.query_params`.
61
62 ---
63
64 ## Serializers
65
66 #### Single-step object creation.
67
68 Previously the serializers used a two-step object creation, as follows:
69
70 1. Validating the data would create an object instance. This instance would be available as `serializer.object`.
71 2. Calling `serializer.save()` would then save the object instance to the database.
72
73 This style is in-line with how the `ModelForm` class works in Django, but is problematic for a number of reasons:
74
75 * 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.
76 * 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.
77 * 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?
78
79 We now use single-step object creation, like so:
80
81 1. Validating the data makes the cleaned data available as `serializer.validated_data`.
82 2. Calling `serializer.save()` then saves and returns the new object instance.
83
84 The resulting API changes are further detailed below.
85
86 #### The `.create()` and `.update()` methods.
87
88 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()`.
89
90 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.
91
92 These methods also replace the optional `.save_object()` method, which no longer exists.
93
94 The following example from the tutorial previously used `restore_object()` to handle both creating and updating object instances.
95
96 def restore_object(self, attrs, instance=None):
97 if instance:
98 # Update existing instance
99 instance.title = attrs.get('title', instance.title)
100 instance.code = attrs.get('code', instance.code)
101 instance.linenos = attrs.get('linenos', instance.linenos)
102 instance.language = attrs.get('language', instance.language)
103 instance.style = attrs.get('style', instance.style)
104 return instance
105
106 # Create new instance
107 return Snippet(**attrs)
108
109 This would now be split out into two separate methods.
110
111 def update(self, instance, validated_data):
112 instance.title = validated_data.get('title', instance.title)
113 instance.code = validated_data.get('code', instance.code)
114 instance.linenos = validated_data.get('linenos', instance.linenos)
115 instance.language = validated_data.get('language', instance.language)
116 instance.style = validated_data.get('style', instance.style)
117 instance.save()
118 return instance
119
120 def create(self, validated_data):
121 return Snippet.objects.create(**validated_data)
122
123 Note that these methods should return the newly created object instance.
124
125 #### Use `.validated_data` instead of `.object`.
126
127 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.
128
129 For example the following code *is no longer valid*:
130
131 if serializer.is_valid():
132 name = serializer.object.name # Inspect validated field data.
133 logging.info('Creating ticket "%s"' % name)
134 serializer.object.user = request.user # Include the user when saving.
135 serializer.save()
136
137 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.
138
139 The corresponding code would now look like this:
140
141 if serializer.is_valid():
142 name = serializer.validated_data['name'] # Inspect validated field data.
143 logging.info('Creating ticket "%s"' % name)
144 serializer.save(user=request.user) # Include the user when saving.
145
146 #### Using `.is_valid(raise_exception=True)`
147
148 The `.is_valid()` method now takes an optional boolean flag, `raise_exception`.
149
150 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.
151
152 The handling and formatting of error responses may be altered globally by using the `EXCEPTION_HANDLER` settings key.
153
154 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.
155
156 #### Using `serializers.ValidationError`.
157
158 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.
159
160 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.
161
162 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.
163
164 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.
165
166 #### Change to `validate_<field_name>`.
167
168 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:
169
170 def validate_score(self, attrs, source):
171 if attrs['score'] % 10 != 0:
172 raise serializers.ValidationError('This field should be a multiple of ten.')
173 return attrs
174
175 This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value.
176
177 def validate_score(self, value):
178 if value % 10 != 0:
179 raise serializers.ValidationError('This field should be a multiple of ten.')
180 return value
181
182 Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual.
183
184 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.
185
186 You can either return `non_field_errors` from the validate method by raising a simple `ValidationError`
187
188 def validate(self, attrs):
189 # serializer.errors == {'non_field_errors': ['A non field error']}
190 raise serializers.ValidationError('A non field error')
191
192 Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the `ValidationError`, like so:
193
194 def validate(self, attrs):
195 # serializer.errors == {'my_field': ['A field error']}
196 raise serializers.ValidationError({'my_field': 'A field error'})
197
198 This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field.
199
200 #### Removal of `transform_<field_name>`.
201
202 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.
203
204 For example:
205
206 def to_representation(self, instance):
207 ret = super(UserSerializer, self).to_representation(instance)
208 ret['username'] = ret['username'].lower()
209 return ret
210
211 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.
212
213 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:
214
215 class BaseModelSerializer(ModelSerializer):
216 """
217 A custom ModelSerializer class that preserves 2.x style `transform_<field_name>` behavior.
218 """
219 def to_representation(self, instance):
220 ret = super(BaseModelSerializer, self).to_representation(instance)
221 for key, value in ret.items():
222 method = getattr(self, 'transform_' + key, None)
223 if method is not None:
224 ret[key] = method(value)
225 return ret
226
227 #### Differences between ModelSerializer validation and ModelForm.
228
229 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.
230
231 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.
232
233 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.
234
235 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.
236
237 def validate(self, attrs):
238 instance = ExampleModel(**attrs)
239 instance.clean()
240 return attrs
241
242 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.
243
244 #### Writable nested serialization.
245
246 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:
247
248 * There can be complex dependencies involved in order of saving multiple related model instances.
249 * It's unclear what behavior the user should expect when related models are passed `None` data.
250 * It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records.
251
252 Using the `depth` option on `ModelSerializer` will now create **read-only nested serializers** by default.
253
254 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:
255
256 >>> class ProfileSerializer(serializers.ModelSerializer):
257 >>> class Meta:
258 >>> model = Profile
259 >>> fields = ['address', 'phone']
260 >>>
261 >>> class UserSerializer(serializers.ModelSerializer):
262 >>> profile = ProfileSerializer()
263 >>> class Meta:
264 >>> model = User
265 >>> fields = ['username', 'email', 'profile']
266 >>>
267 >>> data = {
268 >>> 'username': 'lizzy',
269 >>> 'email': '[email protected]',
270 >>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}
271 >>> }
272 >>>
273 >>> serializer = UserSerializer(data=data)
274 >>> serializer.save()
275 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.
276
277 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.
278
279 class UserSerializer(serializers.ModelSerializer):
280 profile = ProfileSerializer()
281
282 class Meta:
283 model = User
284 fields = ['username', 'email', 'profile']
285
286 def create(self, validated_data):
287 profile_data = validated_data.pop('profile')
288 user = User.objects.create(**validated_data)
289 Profile.objects.create(user=user, **profile_data)
290 return user
291
292 The single-step object creation makes this far simpler and more obvious than the previous `.restore_object()` behavior.
293
294 #### Printable serializer representations.
295
296 Serializer instances now support a printable representation that allows you to inspect the fields present on the instance.
297
298 For instance, given the following example model:
299
300 class LocationRating(models.Model):
301 location = models.CharField(max_length=100)
302 rating = models.IntegerField()
303 created_by = models.ForeignKey(User)
304
305 Let's create a simple `ModelSerializer` class corresponding to the `LocationRating` model.
306
307 class LocationRatingSerializer(serializer.ModelSerializer):
308 class Meta:
309 model = LocationRating
310
311 We can now inspect the serializer representation in the Django shell, using `python manage.py shell`...
312
313 >>> serializer = LocationRatingSerializer()
314 >>> print(serializer) # Or use `print serializer` in Python 2.x
315 LocationRatingSerializer():
316 id = IntegerField(label='ID', read_only=True)
317 location = CharField(max_length=100)
318 rating = IntegerField()
319 created_by = PrimaryKeyRelatedField(queryset=User.objects.all())
320
321 #### The `extra_kwargs` option.
322
323 The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDeprecation` and replaced with a more generic `extra_kwargs`.
324
325 class MySerializer(serializer.ModelSerializer):
326 class Meta:
327 model = MyModel
328 fields = ['id', 'email', 'notes', 'is_admin']
329 extra_kwargs = {
330 'is_admin': {'write_only': True}
331 }
332
333 Alternatively, specify the field explicitly on the serializer class:
334
335 class MySerializer(serializer.ModelSerializer):
336 is_admin = serializers.BooleanField(write_only=True)
337
338 class Meta:
339 model = MyModel
340 fields = ['id', 'email', 'notes', 'is_admin']
341
342 The `read_only_fields` option remains as a convenient shortcut for the more common case.
343
344 #### Changes to `HyperlinkedModelSerializer`.
345
346 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:
347
348 class MySerializer(serializer.HyperlinkedModelSerializer):
349 class Meta:
350 model = MyModel
351 fields = ['url', 'email', 'notes', 'is_admin']
352 extra_kwargs = {
353 'url': {'lookup_field': 'uuid'}
354 }
355
356 Alternatively, specify the field explicitly on the serializer class:
357
358 class MySerializer(serializer.HyperlinkedModelSerializer):
359 url = serializers.HyperlinkedIdentityField(
360 view_name='mymodel-detail',
361 lookup_field='uuid'
362 )
363
364 class Meta:
365 model = MyModel
366 fields = ['url', 'email', 'notes', 'is_admin']
367
368 #### Fields for model methods and properties.
369
370 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:
371
372 class Invitation(models.Model):
373 created = models.DateTimeField()
374 to_email = models.EmailField()
375 message = models.CharField(max_length=1000)
376
377 def expiry_date(self):
378 return self.created + datetime.timedelta(days=30)
379
380 You can include `expiry_date` as a field option on a `ModelSerializer` class.
381
382 class InvitationSerializer(serializers.ModelSerializer):
383 class Meta:
384 model = Invitation
385 fields = ['to_email', 'message', 'expiry_date']
386
387 These fields will be mapped to `serializers.ReadOnlyField()` instances.
388
389 >>> serializer = InvitationSerializer()
390 >>> print(repr(serializer))
391 InvitationSerializer():
392 to_email = EmailField(max_length=75)
393 message = CharField(max_length=1000)
394 expiry_date = ReadOnlyField()
395
396 #### The `ListSerializer` class.
397
398 The `ListSerializer` class has now been added, and allows you to create base serializer classes for only accepting multiple inputs.
399
400 class MultipleUserSerializer(ListSerializer):
401 child = UserSerializer()
402
403 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.
404
405 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.
406
407 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.
408
409 #### The `BaseSerializer` class.
410
411 REST framework now includes a simple `BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles.
412
413 This class implements the same basic API as the `Serializer` class:
414
415 * `.data` - Returns the outgoing primitive representation.
416 * `.is_valid()` - Deserializes and validates incoming data.
417 * `.validated_data` - Returns the validated incoming data.
418 * `.errors` - Returns an errors during validation.
419 * `.save()` - Persists the validated data into an object instance.
420
421 There are four methods that can be overridden, depending on what functionality you want the serializer class to support:
422
423 * `.to_representation()` - Override this to support serialization, for read operations.
424 * `.to_internal_value()` - Override this to support deserialization, for write operations.
425 * `.create()` and `.update()` - Override either or both of these to support saving instances.
426
427 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`.
428
429 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.
430
431 ##### Read-only `BaseSerializer` classes.
432
433 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:
434
435 class HighScore(models.Model):
436 created = models.DateTimeField(auto_now_add=True)
437 player_name = models.CharField(max_length=10)
438 score = models.IntegerField()
439
440 It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types.
441
442 class HighScoreSerializer(serializers.BaseSerializer):
443 def to_representation(self, obj):
444 return {
445 'score': obj.score,
446 'player_name': obj.player_name
447 }
448
449 We can now use this class to serialize single `HighScore` instances:
450
451 @api_view(['GET'])
452 def high_score(request, pk):
453 instance = HighScore.objects.get(pk=pk)
454 serializer = HighScoreSerializer(instance)
455 return Response(serializer.data)
456
457 Or use it to serialize multiple instances:
458
459 @api_view(['GET'])
460 def all_high_scores(request):
461 queryset = HighScore.objects.order_by('-score')
462 serializer = HighScoreSerializer(queryset, many=True)
463 return Response(serializer.data)
464
465 ##### Read-write `BaseSerializer` classes.
466
467 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.
468
469 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`.
470
471 If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods.
472
473 Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations.
474
475 class HighScoreSerializer(serializers.BaseSerializer):
476 def to_internal_value(self, data):
477 score = data.get('score')
478 player_name = data.get('player_name')
479
480 # Perform the data validation.
481 if not score:
482 raise ValidationError({
483 'score': 'This field is required.'
484 })
485 if not player_name:
486 raise ValidationError({
487 'player_name': 'This field is required.'
488 })
489 if len(player_name) > 10:
490 raise ValidationError({
491 'player_name': 'May not be more than 10 characters.'
492 })
493
494 # Return the validated values. This will be available as
495 # the `.validated_data` property.
496 return {
497 'score': int(score),
498 'player_name': player_name
499 }
500
501 def to_representation(self, obj):
502 return {
503 'score': obj.score,
504 'player_name': obj.player_name
505 }
506
507 def create(self, validated_data):
508 return HighScore.objects.create(**validated_data)
509
510 #### Creating new generic serializers with `BaseSerializer`.
511
512 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.
513
514 The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
515
516 class ObjectSerializer(serializers.BaseSerializer):
517 """
518 A read-only serializer that coerces arbitrary complex objects
519 into primitive representations.
520 """
521 def to_representation(self, obj):
522 for attribute_name in dir(obj):
523 attribute = getattr(obj, attribute_name)
524 if attribute_name.startswith('_'):
525 # Ignore private attributes.
526 pass
527 elif hasattr(attribute, '__call__'):
528 # Ignore methods and other callables.
529 pass
530 elif isinstance(attribute, (str, int, bool, float, type(None))):
531 # Primitive types can be passed through unmodified.
532 output[attribute_name] = attribute
533 elif isinstance(attribute, list):
534 # Recursively deal with items in lists.
535 output[attribute_name] = [
536 self.to_representation(item) for item in attribute
537 ]
538 elif isinstance(attribute, dict):
539 # Recursively deal with items in dictionaries.
540 output[attribute_name] = {
541 str(key): self.to_representation(value)
542 for key, value in attribute.items()
543 }
544 else:
545 # Force anything else to its string representation.
546 output[attribute_name] = str(attribute)
547
548 ---
549
550 ## Serializer fields
551
552 #### The `Field` and `ReadOnly` field classes.
553
554 There are some minor tweaks to the field base classes.
555
556 Previously we had these two base classes:
557
558 * `Field` as the base class for read-only fields. A default implementation was included for serializing data.
559 * `WritableField` as the base class for read-write fields.
560
561 We now use the following:
562
563 * `Field` is the base class for all fields. It does not include any default implementation for either serializing or deserializing data.
564 * `ReadOnlyField` is a concrete implementation for read-only fields that simply returns the attribute value without modification.
565
566 #### The `required`, `allow_null`, `allow_blank` and `default` arguments.
567
568 REST framework now has more explicit and clear control over validating empty values for fields.
569
570 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.
571
572 We now have a better separation, with separate `required`, `allow_null` and `allow_blank` arguments.
573
574 The following set of arguments are used to control validation of empty values:
575
576 * `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.
577 * `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.
578 * `allow_null=True`: `None` is a valid input.
579 * `allow_blank=True`: `''` is valid input. For `CharField` and subclasses only.
580
581 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.
582
583 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.
584
585 #### Coercing output types.
586
587 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.
588
589 #### Removal of `.validate()`.
590
591 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()`.
592
593 class UppercaseCharField(serializers.CharField):
594 def to_internal_value(self, data):
595 value = super(UppercaseCharField, self).to_internal_value(data)
596 if value != value.upper():
597 raise serializers.ValidationError('The input should be uppercase only.')
598 return value
599
600 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.
601
602 #### The `ListField` class.
603
604 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:
605
606 scores = ListField(child=IntegerField(min_value=0, max_value=100))
607
608 You can also use a declarative style to create new subclasses of `ListField`, like this:
609
610 class ScoresField(ListField):
611 child = IntegerField(min_value=0, max_value=100)
612
613 We can now use the `ScoresField` class inside another serializer:
614
615 scores = ScoresField()
616
617 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.
618
619 #### The `ChoiceField` class may now accept a flat list.
620
621 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:
622
623 color = ChoiceField(choices=['red', 'green', 'blue'])
624
625 #### The `MultipleChoiceField` class.
626
627 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.
628
629 #### Changes to the custom field API.
630
631 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)`.
632
633 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...
634
635 def field_to_native(self, obj, field_name):
636 """A custom read-only field that returns the class name."""
637 return obj.__class__.__name__
638
639 Now if you need to access the entire object you'll instead need to override one or both of the following:
640
641 * Use `get_attribute` to modify the attribute value passed to `to_representation()`.
642 * Use `get_value` to modify the data value passed `to_internal_value()`.
643
644 For example:
645
646 def get_attribute(self, obj):
647 # Pass the entire object through to `to_representation()`,
648 # instead of the standard attribute lookup.
649 return obj
650
651 def to_representation(self, value):
652 return value.__class__.__name__
653
654 #### Explicit `queryset` required on relational fields.
655
656 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`.
657
658 This code *would be valid* in `2.4.3`:
659
660 class AccountSerializer(serializers.ModelSerializer):
661 organizations = serializers.SlugRelatedField(slug_field='name')
662
663 class Meta:
664 model = Account
665
666 However this code *would not be valid* in `3.0`:
667
668 # Missing `queryset`
669 class AccountSerializer(serializers.Serializer):
670 organizations = serializers.SlugRelatedField(slug_field='name')
671
672 def restore_object(self, attrs, instance=None):
673 # ...
674
675 The queryset argument is now always required for writable relational fields.
676 This removes some magic and makes it easier and more obvious to move between implicit `ModelSerializer` classes and explicit `Serializer` classes.
677
678 class AccountSerializer(serializers.ModelSerializer):
679 organizations = serializers.SlugRelatedField(
680 slug_field='name',
681 queryset=Organization.objects.all()
682 )
683
684 class Meta:
685 model = Account
686
687 The `queryset` argument is only ever required for writable fields, and is not required or valid for fields with `read_only=True`.
688
689 #### Optional argument to `SerializerMethodField`.
690
691 The argument to `SerializerMethodField` is now optional, and defaults to `get_<field_name>`. For example the following is valid:
692
693 class AccountSerializer(serializers.Serializer):
694 # `method_name='get_billing_details'` by default.
695 billing_details = serializers.SerializerMethodField()
696
697 def get_billing_details(self, account):
698 return calculate_billing(account)
699
700 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*:
701
702 billing_details = serializers.SerializerMethodField('get_billing_details')
703
704 #### Enforcing consistent `source` usage.
705
706 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.
707
708 The following usage will *now raise an error*:
709
710 email = serializers.EmailField(source='email')
711
712 #### The `UniqueValidator` and `UniqueTogetherValidator` classes.
713
714 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`.
715
716 The `UniqueValidator` should be applied to a serializer field, and takes a single `queryset` argument.
717
718 from rest_framework import serializers
719 from rest_framework.validators import UniqueValidator
720
721 class OrganizationSerializer(serializers.Serializer):
722 url = serializers.HyperlinkedIdentityField(view_name='organization_detail')
723 created = serializers.DateTimeField(read_only=True)
724 name = serializers.CharField(
725 max_length=100,
726 validators=UniqueValidator(queryset=Organization.objects.all())
727 )
728
729 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.
730
731 class RaceResultSerializer(serializers.Serializer):
732 category = serializers.ChoiceField(['5k', '10k'])
733 position = serializers.IntegerField()
734 name = serializers.CharField(max_length=100)
735
736 class Meta:
737 validators = [UniqueTogetherValidator(
738 queryset=RaceResult.objects.all(),
739 fields=['category', 'position']
740 )]
741
742 #### The `UniqueForDateValidator` classes.
743
744 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()`.
745
746 These classes are documented in the [Validators](../api-guide/validators.md) section of the documentation.
747
748 ---
749
750 ## Generic views
751
752 #### Simplification of view logic.
753
754 The view logic for the default method handlers has been significantly simplified, due to the new serializers API.
755
756 #### Changes to pre/post save hooks.
757
758 The `pre_save` and `post_save` hooks no longer exist, but are replaced with `perform_create(self, serializer)` and `perform_update(self, serializer)`.
759
760 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.
761
762 For example:
763
764 def perform_create(self, serializer):
765 # Include the owner attribute directly, rather than from request data.
766 instance = serializer.save(owner=self.request.user)
767 # Perform a custom post-save action.
768 send_email(instance.to_email, instance.message)
769
770 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.
771
772 def perform_destroy(self, instance):
773 # Perform a custom pre-delete action.
774 send_deletion_alert(user=instance.created_by, deleted=instance)
775 # Delete the object instance.
776 instance.delete()
777
778 #### Removal of view attributes.
779
780 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.
781
782 I would personally recommend that developers treat view instances as immutable objects in their application code.
783
784 #### PUT as create.
785
786 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.
787
788 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.
789
790 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.
791
792 #### Customizing error responses.
793
794 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.
795
796 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.
797
798 ---
799
800 ## The metadata API
801
802 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.
803
804 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.
805
806 ---
807
808 ## Serializers as HTML forms
809
810 REST framework 3.0 includes templated HTML form rendering for serializers.
811
812 This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.
813
814 Significant changes that you do need to be aware of include:
815
816 * 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.
817 * Nested lists of HTML forms are not yet supported, but are planned for 3.1.
818 * 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.
819
820 #### The `style` keyword argument for serializer fields.
821
822 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.
823
824 For example, to use a `textarea` control instead of the default `input` control, you would use the following…
825
826 additional_notes = serializers.CharField(
827 style={'base_template': 'textarea.html'}
828 )
829
830 Similarly, to use a radio button control instead of the default `select` control, you would use the following…
831
832 color_channel = serializers.ChoiceField(
833 choices=['red', 'blue', 'green'],
834 style={'base_template': 'radio.html'}
835 )
836
837 This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.
838
839 ---
840
841 ## API style
842
843 There are some improvements in the default style we use in our API responses.
844
845 #### Unicode JSON by default.
846
847 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:
848
849 REST_FRAMEWORK = {
850 'UNICODE_JSON': False
851 }
852
853 #### Compact JSON by default.
854
855 We now output compact JSON in responses by default. For example, we return:
856
857 {"email":"[email protected]","is_admin":true}
858
859 Instead of the following:
860
861 {"email": "[email protected]", "is_admin": true}
862
863 The `COMPACT_JSON` setting has been added, and can be used to revert this behavior if needed:
864
865 REST_FRAMEWORK = {
866 'COMPACT_JSON': False
867 }
868
869 #### File fields as URLs
870
871 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).
872
873 You can revert this behavior, and display filenames in the representation by using the `UPLOADED_FILES_USE_URL` settings key:
874
875 REST_FRAMEWORK = {
876 'UPLOADED_FILES_USE_URL': False
877 }
878
879 You can also modify serializer fields individually, using the `use_url` argument:
880
881 uploaded_file = serializers.FileField(use_url=False)
882
883 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:
884
885 context = {'request': request}
886 serializer = ExampleSerializer(instance, context=context)
887 return Response(serializer.data)
888
889 If the request is omitted from the context, the returned URLs will be of the form `/url_path/filename.txt`.
890
891 #### Throttle headers using `Retry-After`.
892
893 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.
894
895 #### Date and time objects as ISO-8601 strings in serializer data.
896
897 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.
898
899 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.
900
901 REST_FRAMEWORK = {
902 # Return native `Date` and `Time` objects in `serializer.data`
903 'DATETIME_FORMAT': None
904 'DATE_FORMAT': None
905 'TIME_FORMAT': None
906 }
907
908 You can also modify serializer fields individually, using the `date_format`, `time_format` and `datetime_format` arguments:
909
910 # Return `DateTime` instances in `serializer.data`, not strings.
911 created = serializers.DateTimeField(format=None)
912
913 #### Decimals as strings in serializer data.
914
915 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.
916
917 You can modify this behavior globally by using the `COERCE_DECIMAL_TO_STRING` settings key.
918
919 REST_FRAMEWORK = {
920 'COERCE_DECIMAL_TO_STRING': False
921 }
922
923 Or modify it on an individual serializer field, using the `coerce_to_string` keyword argument.
924
925 # Return `Decimal` instances in `serializer.data`, not strings.
926 amount = serializers.DecimalField(
927 max_digits=10,
928 decimal_places=2,
929 coerce_to_string=False
930 )
931
932 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.
933
934 ---
935
936 ## Miscellaneous notes
937
938 * 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.
939 * 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.
940 * 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.
941 * `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.
942
943 ---
944
945 ## What's coming next
946
947 3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.
948
949 The 3.1 release is planned to address improvements in the following components:
950
951 * Public API for using serializers as HTML forms.
952 * Request parsing, mediatypes & the implementation of the browsable API.
953 * Introduction of a new pagination API.
954 * Better support for API versioning.
955
956 The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.
957
958 You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/encode/django-rest-framework/milestones).
959
960 [kickstarter]: https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3
961 [sponsors]: https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors
962 [mixins.py]: https://github.com/encode/django-rest-framework/blob/main/rest_framework/mixins.py
963 [django-localization]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#localization-how-to-create-language-files