mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-30 05:24:00 +03:00
265 lines
13 KiB
Markdown
265 lines
13 KiB
Markdown
# Django REST framework 2.3
|
|
|
|
REST framework 2.3 makes it even quicker and easier to build your Web APIs.
|
|
|
|
## ViewSets and Routers
|
|
|
|
The 2.3 release introduces the [ViewSet][viewset] and [Router][router] classes.
|
|
|
|
A viewset is simply a type of class based view that allows you to group multiple views into a single common class.
|
|
|
|
Routers allow you to automatically determine the URLconf for your viewset classes.
|
|
|
|
As an example of just how simple REST framework APIs can now be, here's an API written in a single `urls.py` module:
|
|
|
|
"""
|
|
A REST framework API for viewing and editing users and groups.
|
|
"""
|
|
from django.conf.urls.defaults import url, include
|
|
from django.contrib.auth.models import User, Group
|
|
from rest_framework import viewsets, routers
|
|
|
|
|
|
# ViewSets define the view behavior.
|
|
class UserViewSet(viewsets.ModelViewSet):
|
|
model = User
|
|
|
|
class GroupViewSet(viewsets.ModelViewSet):
|
|
model = Group
|
|
|
|
|
|
# Routers provide an easy way of automatically determining the URL conf
|
|
router = routers.DefaultRouter()
|
|
router.register(r'users', UserViewSet)
|
|
router.register(r'groups', GroupViewSet)
|
|
|
|
|
|
# Wire up our API using automatic URL routing.
|
|
# Additionally, we include login URLs for the browsable API.
|
|
urlpatterns = [
|
|
url(r'^', include(router.urls)),
|
|
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
|
|
]
|
|
|
|
The best place to get started with ViewSets and Routers is to take a look at the [newest section in the tutorial][part-6], which demonstrates their usage.
|
|
|
|
## Simpler views
|
|
|
|
This release rationalises the API and implementation of the generic views, dropping the dependency on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with.
|
|
|
|
This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses.
|
|
|
|
## Easier Serializers
|
|
|
|
REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships.
|
|
|
|
The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the `fields` metadata of the serializer class.
|
|
|
|
For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class.
|
|
|
|
class BlogSerializer(serializers.ModelSerializer):
|
|
comments = serializers.PrimaryKeyRelatedField(many=True)
|
|
|
|
class Meta:
|
|
model = Blog
|
|
fields = ('id', 'title', 'created', 'comments')
|
|
|
|
As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship.
|
|
|
|
class BlogSerializer(serializers.ModelSerializer):
|
|
"""
|
|
Don't need to specify the 'comments' field explicitly anymore.
|
|
"""
|
|
class Meta:
|
|
model = Blog
|
|
fields = ('id', 'title', 'created', 'comments')
|
|
|
|
Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata.
|
|
|
|
class BlogSerializer(serializers.HyperlinkedModelSerializer):
|
|
"""
|
|
This is a hyperlinked serializer, which default to using
|
|
a field named 'url' as the primary identifier.
|
|
Note that we can now easily also add in the 'id' field.
|
|
"""
|
|
class Meta:
|
|
model = Blog
|
|
fields = ('url', 'id', 'title', 'created', 'comments')
|
|
|
|
## More flexible filtering
|
|
|
|
The `FILTER_BACKEND` setting has moved to pending deprecation, in favor of a `DEFAULT_FILTER_BACKENDS` setting that takes a *list* of filter backend classes, instead of a single filter backend class.
|
|
|
|
The generic view `filter_backend` attribute has also been moved to pending deprecation in favor of a `filter_backends` setting.
|
|
|
|
Being able to specify multiple filters will allow for more flexible, powerful behavior. New filter classes to handle searching and ordering of results are planned to be released shortly.
|
|
|
|
---
|
|
|
|
# API Changes
|
|
|
|
## Simplified generic view classes
|
|
|
|
The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView` base classes has now been moved into the base class `GenericAPIView`. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary.
|
|
|
|
Additionally the base generic view no longer inherits from Django's `SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase.
|
|
|
|
Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continues to be supported, but will raise a `PendingDeprecationWarning`. You should instead simply use `GenericAPIView` as the base for any generic view subclasses.
|
|
|
|
### Removed attributes
|
|
|
|
The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed.
|
|
|
|
* context_object_name
|
|
* get_context_data()
|
|
* get_context_object_name()
|
|
|
|
The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed.
|
|
|
|
* paginator_class
|
|
* get_paginator()
|
|
* get_allow_empty()
|
|
* get_slug_field()
|
|
|
|
There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases.
|
|
|
|
Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy.
|
|
|
|
### Simplified methods
|
|
|
|
The `get_object` and `get_paginate_by` methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple.
|
|
|
|
Using an optional queryset with these methods continues to be supported, but will raise a `PendingDeprecationWarning`.
|
|
|
|
The `paginate_queryset` method no longer takes a `page_size` argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a `page` object with an appropriate page size, or returns `None`, if pagination is not configured for the view.
|
|
|
|
Using the `page_size` argument is still supported and will trigger the old-style return type, but will raise a `PendingDeprecationWarning`.
|
|
|
|
### Deprecated attributes
|
|
|
|
The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state.
|
|
|
|
* pk_url_kwarg = 'pk'
|
|
* slug_url_kwarg = 'slug'
|
|
* slug_field = 'slug'
|
|
|
|
Their usage is replaced with a single attribute:
|
|
|
|
* lookup_field = 'pk'
|
|
|
|
This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the `lookup_field` argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name.
|
|
|
|
For example, a view with 'username' based lookup might look like this:
|
|
|
|
class UserDetail(generics.RetrieveAPIView):
|
|
lookup_field = 'username'
|
|
queryset = User.objects.all()
|
|
serializer_class = UserSerializer
|
|
|
|
And would have the following entry in the urlconf:
|
|
|
|
url(r'^users/(?P<username>\w+)/$', UserDetail.as_view()),
|
|
|
|
Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
|
|
|
|
The `allow_empty` attribute is also deprecated. To use `allow_empty=False` style behavior you should explicitly override `get_queryset` and raise an `Http404` on empty querysets.
|
|
|
|
For example:
|
|
|
|
class DisallowEmptyQuerysetMixin(object):
|
|
def get_queryset(self):
|
|
queryset = super(DisallowEmptyQuerysetMixin, self).get_queryset()
|
|
if not queryset.exists():
|
|
raise Http404
|
|
return queryset
|
|
|
|
In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views.
|
|
|
|
## Simpler URL lookups
|
|
|
|
The `HyperlinkedRelatedField` class now takes a single optional `lookup_field` argument, that replaces the `pk_url_kwarg`, `slug_url_kwarg`, and `slug_field` arguments.
|
|
|
|
For example, you might have a field that references it's relationship by a hyperlink based on a slug field:
|
|
|
|
account = HyperlinkedRelatedField(read_only=True,
|
|
lookup_field='slug',
|
|
view_name='account-detail')
|
|
|
|
Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`.
|
|
|
|
## FileUploadParser
|
|
|
|
2.3 adds a `FileUploadParser` parser class, that supports raw file uploads, in addition to the existing multipart upload support.
|
|
|
|
## DecimalField
|
|
|
|
2.3 introduces a `DecimalField` serializer field, which returns `Decimal` instances.
|
|
|
|
For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering `Decimal` instances to your renderer implementation.
|
|
|
|
## ModelSerializers and reverse relationships
|
|
|
|
The support for adding reverse relationships to the `fields` option on a `ModelSerializer` class means that the `get_related_field` and `get_nested_field` method signatures have now changed.
|
|
|
|
In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now `(self, model_field, related_model, to_many)`. For reverse relationships `model_field` will be `None`.
|
|
|
|
The old-style signature will continue to function but will raise a `PendingDeprecationWarning`.
|
|
|
|
## View names and descriptions
|
|
|
|
The mechanics of how the names and descriptions used in the browsable API are generated has been modified and cleaned up somewhat.
|
|
|
|
If you've been customizing this behavior, for example perhaps to use `rst` markup for the browsable API, then you'll need to take a look at the implementation to see what updates you need to make.
|
|
|
|
Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated.
|
|
|
|
---
|
|
|
|
# Other notes
|
|
|
|
## More explicit style
|
|
|
|
The usage of `model` attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explicit `queryset` and `serializer_class` attributes.
|
|
|
|
For example, the following is now the recommended style for using generic views:
|
|
|
|
class AccountListView(generics.RetrieveAPIView):
|
|
queryset = MyModel.objects.all()
|
|
serializer_class = MyModelSerializer
|
|
|
|
Using an explicit `queryset` and `serializer_class` attributes makes the functioning of the view more clear than using the shortcut `model` attribute.
|
|
|
|
It also makes the usage of the `get_queryset()` or `get_serializer_class()` methods more obvious.
|
|
|
|
class AccountListView(generics.RetrieveAPIView):
|
|
serializer_class = MyModelSerializer
|
|
|
|
def get_queryset(self):
|
|
"""
|
|
Determine the queryset dynamically, depending on the
|
|
user making the request.
|
|
|
|
Note that overriding this method follows on more obviously now
|
|
that an explicit `queryset` attribute is the usual view style.
|
|
"""
|
|
return self.user.accounts
|
|
|
|
## Django 1.3 support
|
|
|
|
The 2.3.x release series will be the last series to provide compatibility with Django 1.3.
|
|
|
|
## Version 2.2 API changes
|
|
|
|
All API changes in 2.2 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default.
|
|
|
|
## What comes next?
|
|
|
|
* Support for read-write nested serializers is almost complete, and due to be released in the next few weeks.
|
|
* Extra filter backends for searching and ordering of results are planned to be added shortly.
|
|
|
|
The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September.
|
|
|
|
[viewset]: ../api-guide/viewsets.md
|
|
[router]: ../api-guide/routers.md
|
|
[part-6]: ../tutorial/6-viewsets-and-routers.md
|