From 43d3634e892e303ca377265d3176e8313f19563f Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 30 Sep 2012 15:55:24 +0100 Subject: [PATCH 01/15] Docs tweaking --- docs/api-guide/authentication.md | 8 ++++---- docs/api-guide/responses.md | 24 ++++++++++++++++++------ rest_framework/response.py | 2 ++ 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index f24c6a81b..c69953607 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -39,6 +39,7 @@ You can also set the authentication policy on a per-view basis, using the `APIVi class ExampleView(APIView): authentication_classes = (SessionAuthentication, UserBasicAuthentication) + permission_classes = (IsAuthenticated,) def get(self, request, format=None): content = { @@ -49,10 +50,9 @@ You can also set the authentication policy on a per-view basis, using the `APIVi Or, if you're using the `@api_view` decorator with function based views. - @api_view( - allowed=('GET',), - authentication_classes=(SessionAuthentication, UserBasicAuthentication) - ) + @api_view('GET'), + @authentication_classes(SessionAuthentication, UserBasicAuthentication) + @permissions_classes(IsAuthenticated) def example_view(request, format=None): content = { 'user': unicode(request.user), # `django.contrib.auth.User` instance. diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md index 6c279f171..e9ebcf819 100644 --- a/docs/api-guide/responses.md +++ b/docs/api-guide/responses.md @@ -8,18 +8,30 @@ REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request. -The `Response` class subclasses Django's `TemplateResponse`. `Response` objects are initialised with content, which should consist of native python primatives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. +The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialised with data, which should consist of native python primatives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. -There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it does provide a better interface for returning Web API responses. +There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` objects from your views if you want, but it provides a nicer interface for returning Web API responses. -## Response(content, headers=None, renderers=None, view=None, format=None, status=None) +Unless you want to heavily customize REST framework for some reason, you should always use an `APIView` class or `@api_view` function for views that return `Response` objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view. +## Response(data, status=None, headers=None) -## .renderers +Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any python primatives. -## .view +The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primative datatypes before creating the `Response` object. -## .format +You can use REST framework's `Serializer` classes to perform this data serialization, or use your own custom serialization. +## .data + +The unrendered content of a `Request` object can be accessed using the `.data` attribute. + +## .content + +To access the rendered content of a `Response` object, you must first call `.render()`. You'll typically only need to do this in cases such as unit testing responses - when you return a `Response` from a view Django's response cycle will handle calling `.render()` for you. + +## .renderer + +When you return a `Response` instance, the `APIView` class or `@api_view` decorator will select the appropriate renderer, and set the `.renderer` attribute on the `Response`, before returning it from the view. [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/ \ No newline at end of file diff --git a/rest_framework/response.py b/rest_framework/response.py index 90516837d..db6bf3e24 100644 --- a/rest_framework/response.py +++ b/rest_framework/response.py @@ -33,6 +33,8 @@ class Response(SimpleTemplateResponse): @property def rendered_content(self): + assert self.renderer, "No renderer set on Response" + self['Content-Type'] = self.renderer.media_type if self.data is None: return self.renderer.render() From 6fa589fefd48d98e4f0a11548b6c3e5ced58e31e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Sun, 30 Sep 2012 17:31:28 +0100 Subject: [PATCH 02/15] Pagination support --- rest_framework/fields.py | 14 +++-- rest_framework/generics.py | 31 +++++++--- rest_framework/mixins.py | 21 ++++++- rest_framework/pagination.py | 34 +++++++++++ rest_framework/settings.py | 6 ++ rest_framework/templatetags/rest_framework.py | 2 +- rest_framework/tests/pagination.py | 57 +++++++++++++++++++ 7 files changed, 151 insertions(+), 14 deletions(-) create mode 100644 rest_framework/pagination.py create mode 100644 rest_framework/tests/pagination.py diff --git a/rest_framework/fields.py b/rest_framework/fields.py index eab90617c..74675ee9f 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -139,7 +139,13 @@ class Field(object): if hasattr(self, 'model_field'): return self.to_native(self.model_field._get_val_from_obj(obj)) - return self.to_native(getattr(obj, self.source or field_name)) + if self.source: + value = obj + for component in self.source.split('.'): + value = getattr(value, component) + else: + value = getattr(obj, field_name) + return self.to_native(value) def to_native(self, value): """ @@ -175,7 +181,7 @@ class RelatedField(Field): """ def field_to_native(self, obj, field_name): - obj = getattr(obj, field_name) + obj = getattr(obj, self.source or field_name) if obj.__class__.__name__ in ('RelatedManager', 'ManyRelatedManager'): return [self.to_native(item) for item in obj.all()] return self.to_native(obj) @@ -215,10 +221,10 @@ class PrimaryKeyRelatedField(RelatedField): def field_to_native(self, obj, field_name): try: - obj = obj.serializable_value(field_name) + obj = obj.serializable_value(self.source or field_name) except AttributeError: field = obj._meta.get_field_by_name(field_name)[0] - obj = getattr(obj, field_name) + obj = getattr(obj, self.source or field_name) if obj.__class__.__name__ == 'RelatedManager': return [self.to_native(item.pk) for item in obj.all()] elif isinstance(field, RelatedObject): diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 4240e33e4..1e547b32e 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -2,7 +2,8 @@ Generic views that provide commmonly needed behaviour. """ -from rest_framework import views, mixins, serializers +from rest_framework import views, mixins +from rest_framework.settings import api_settings from django.views.generic.detail import SingleObjectMixin from django.views.generic.list import MultipleObjectMixin @@ -14,23 +15,37 @@ class BaseView(views.APIView): Base class for all other generic views. """ serializer_class = None + model_serializer_class = api_settings.MODEL_SERIALIZER + pagination_serializer_class = api_settings.PAGINATION_SERIALIZER + paginate_by = api_settings.PAGINATE_BY - def get_serializer(self, data=None, files=None, instance=None): + def get_serializer_context(self): + return { + 'request': self.request, + 'format': self.kwargs.get('format', None) + } + + def get_serializer(self, data=None, files=None, instance=None, kwargs=None): # TODO: add support for files # TODO: add support for seperate serializer/deserializer serializer_class = self.serializer_class + kwargs = kwargs or {} if serializer_class is None: - class DefaultSerializer(serializers.ModelSerializer): + class DefaultSerializer(self.model_serializer_class): class Meta: model = self.model serializer_class = DefaultSerializer - context = { - 'request': self.request, - 'format': self.kwargs.get('format', None) - } - return serializer_class(data, instance=instance, context=context) + context = self.get_serializer_context() + return serializer_class(data, instance=instance, context=context, **kwargs) + + def get_pagination_serializer(self, page=None): + serializer_class = self.pagination_serializer_class + context = self.get_serializer_context() + ret = serializer_class(instance=page, context=context) + ret.fields['results'] = self.get_serializer(kwargs={'source': 'object_list'}) + return ret class MultipleObjectBaseView(MultipleObjectMixin, BaseView): diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py index fe12dc8ff..167cd89aa 100644 --- a/rest_framework/mixins.py +++ b/rest_framework/mixins.py @@ -7,6 +7,7 @@ which allows mixin classes to be composed in interesting ways. Eg. Use mixins to build a Resource class, and have a Router class perform the binding of http methods to actions for us. """ +from django.http import Http404 from rest_framework import status from rest_framework.response import Response @@ -30,9 +31,27 @@ class ListModelMixin(object): List a queryset. Should be mixed in with `MultipleObjectBaseView`. """ + empty_error = u"Empty list and '%(class_name)s.allow_empty' is False." + def list(self, request, *args, **kwargs): self.object_list = self.get_queryset() - serializer = self.get_serializer(instance=self.object_list) + + # Default is to allow empty querysets. This can be altered by setting + # `.allow_empty = False`, to raise 404 errors on empty querysets. + allow_empty = self.get_allow_empty() + if not allow_empty and len(self.object_list) == 0: + error_args = {'class_name': self.__class__.__name__} + raise Http404(self.empty_error % error_args) + + # Pagination size is set by the `.paginate_by` attribute, + # which may be `None` to disable pagination. + page_size = self.get_paginate_by(self.object_list) + if page_size: + paginator, page, queryset, is_paginated = self.paginate_queryset(self.object_list, page_size) + serializer = self.get_pagination_serializer(page) + else: + serializer = self.get_serializer(instance=self.object_list) + return Response(serializer.data) diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py new file mode 100644 index 000000000..398e6f3d5 --- /dev/null +++ b/rest_framework/pagination.py @@ -0,0 +1,34 @@ +from rest_framework import serializers + +# TODO: Support URLconf kwarg-style paging + + +class NextPageField(serializers.Field): + def to_native(self, value): + if not value.has_next(): + return None + page = value.next_page_number() + request = self.context['request'] + return request.build_absolute_uri('?page=%d' % page) + + +class PreviousPageField(serializers.Field): + def to_native(self, value): + if not value.has_previous(): + return None + page = value.previous_page_number() + request = self.context['request'] + return request.build_absolute_uri('?page=%d' % page) + + +class PaginationSerializer(serializers.Serializer): + count = serializers.Field(source='paginator.count') + next = NextPageField(source='*') + previous = PreviousPageField(source='*') + + def to_native(self, obj): + """ + Prevent default behaviour of iterating over elements, and serializing + each in turn. + """ + return self.convert_object(obj) diff --git a/rest_framework/settings.py b/rest_framework/settings.py index cfc89fe1a..8387fd294 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -44,6 +44,10 @@ DEFAULTS = { 'anon': None, }, + 'MODEL_SERIALIZER': 'rest_framework.serializers.ModelSerializer', + 'PAGINATION_SERIALIZER': 'rest_framework.pagination.PaginationSerializer', + 'PAGINATE_BY': 20, + 'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser', 'UNAUTHENTICATED_TOKEN': None, @@ -65,6 +69,8 @@ IMPORT_STRINGS = ( 'DEFAULT_PERMISSIONS', 'DEFAULT_THROTTLES', 'DEFAULT_CONTENT_NEGOTIATION', + 'MODEL_SERIALIZER', + 'PAGINATION_SERIALIZER', 'UNAUTHENTICATED_USER', 'UNAUTHENTICATED_TOKEN', ) diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py index 377fd489b..c9b6eb10d 100644 --- a/rest_framework/templatetags/rest_framework.py +++ b/rest_framework/templatetags/rest_framework.py @@ -1,5 +1,5 @@ from django import template -from django.core.urlresolvers import reverse, NoReverseMatch +from django.core.urlresolvers import reverse from django.http import QueryDict from django.utils.encoding import force_unicode from django.utils.html import escape diff --git a/rest_framework/tests/pagination.py b/rest_framework/tests/pagination.py new file mode 100644 index 000000000..4ddfc9157 --- /dev/null +++ b/rest_framework/tests/pagination.py @@ -0,0 +1,57 @@ +from django.test import TestCase +from django.test.client import RequestFactory +from rest_framework import generics, status +from rest_framework.tests.models import BasicModel + +factory = RequestFactory() + + +class RootView(generics.RootAPIView): + """ + Example description for OPTIONS. + """ + model = BasicModel + paginate_by = 10 + + +class TestPaginatedView(TestCase): + def setUp(self): + """ + Create 26 BasicModel intances. + """ + for char in 'abcdefghijklmnopqrstuvwxyz': + BasicModel(text=char * 3).save() + self.objects = BasicModel.objects + self.data = [ + {'id': obj.id, 'text': obj.text} + for obj in self.objects.all() + ] + self.view = RootView.as_view() + + def test_get_paginated_root_view(self): + """ + GET requests to paginated RootAPIView should return paginated results. + """ + request = factory.get('/') + response = self.view(request).render() + self.assertEquals(response.status_code, status.HTTP_200_OK) + self.assertEquals(response.data['count'], 26) + self.assertEquals(response.data['results'], self.data[:10]) + self.assertNotEquals(response.data['next'], None) + self.assertEquals(response.data['previous'], None) + + request = factory.get(response.data['next']) + response = self.view(request).render() + self.assertEquals(response.status_code, status.HTTP_200_OK) + self.assertEquals(response.data['count'], 26) + self.assertEquals(response.data['results'], self.data[10:20]) + self.assertNotEquals(response.data['next'], None) + self.assertNotEquals(response.data['previous'], None) + + request = factory.get(response.data['next']) + response = self.view(request).render() + self.assertEquals(response.status_code, status.HTTP_200_OK) + self.assertEquals(response.data['count'], 26) + self.assertEquals(response.data['results'], self.data[20:]) + self.assertEquals(response.data['next'], None) + self.assertNotEquals(response.data['previous'], None) From b16fb5777168246b1e217640b818a82eb6e2141b Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 1 Oct 2012 15:49:19 +0100 Subject: [PATCH 03/15] Expand pagination support, add docs --- docs/api-guide/pagination.md | 98 ++++++++++++++++++++++++++++++ rest_framework/fields.py | 2 + rest_framework/generics.py | 50 ++++++++++----- rest_framework/pagination.py | 62 ++++++++++++++++--- rest_framework/serializers.py | 2 +- rest_framework/tests/generics.py | 1 + rest_framework/tests/pagination.py | 34 ++++++++++- 7 files changed, 223 insertions(+), 26 deletions(-) create mode 100644 docs/api-guide/pagination.md diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md new file mode 100644 index 000000000..0f0a32b5c --- /dev/null +++ b/docs/api-guide/pagination.md @@ -0,0 +1,98 @@ + + +# Pagination + +> Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. +> +> — [Django documentation][cite] + +REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types. + +## Examples + +Let's start by taking a look at an example from the Django documentation. + + from django.core.paginator import Paginator + objects = ['john', 'paul', 'george', 'ringo'] + paginator = Paginator(objects, 2) + page = paginator.page(1) + page.object_list + # ['john', 'paul'] + +At this point we've got a page object. If we wanted to return this page object as a JSON response, we'd need to provide the client with context such as next and previous links, so that it would be able to page through the remaining results. + + from rest_framework.pagination import PaginationSerializer + serializer = PaginationSerializer(instance=page) + serializer.data + # {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']} + +The `context` argument of the `PaginationSerializer` class may optionally include the request. If the request is included in the context then the next and previous links returned by the serializer will use absolute URLs instead of relative URLs. + + request = RequestFactory().get('/foobar') + serializer = PaginationSerializer(instance=page, context={'request': request}) + serializer.data + # {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']} + +We could now return that data in a `Response` object, and it would be rendered into the correct media type. + +Our first example worked because we were using primative objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself with. + +We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example. + + class UserSerializer(serializers.ModelSerializer): + """ + Serializes user querysets. + """ + class Meta: + model = User + fields = ('username', 'email') + + class PaginatedUserSerializer(pagination.PaginationSerializer): + """ + Serializes page objects of user querysets. + """ + class Meta: + object_serializer_class = UserSerializer + + queryset = User.objects.all() + paginator = Paginator(queryset, 20) + page = paginator.page(1) + serializer = PaginatedUserSerializer(instance=page) + serializer.data + # {'count': 1, 'next': None, 'previous': None, 'results': [{'username': u'admin', 'email': u'admin@example.com'}]} + +## Pagination in the generic views + +The generic class based views `ListAPIView` and `ListCreateAPIView` provide pagination of the returned querysets by default. You can customise this behaviour by altering the pagination style, by modifying the default number of results, or by turning pagination off completely. + +## Setting the default pagination style + +The default pagination style may be set globally, using the `PAGINATION_SERIALIZER` and `PAGINATE_BY` settings. For example. + + REST_FRAMEWORK = { + 'PAGINATION_SERIALIZER': ( + 'example_app.pagination.CustomPaginationSerializer', + ), + 'PAGINATE_BY': 10 + } + +You can also set the pagination style on a per-view basis, using the `ListAPIView` generic class-based view. + + class PaginatedListView(ListAPIView): + model = ExampleModel + pagination_serializer_class = CustomPaginationSerializer + paginate_by = 10 + +## Creating custom pagination serializers + +Override `pagination.BasePaginationSerializer`, and set the fields that you want the serializer to return. + +For example. + + class CustomPaginationSerializer(pagination.BasePaginationSerializer): + next = pagination.NextURLField() + total_results = serializers.Field(source='paginator.count') + + +[cite]: https://docs.djangoproject.com/en/dev/topics/pagination/ + diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 74675ee9f..e1a551d37 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -158,6 +158,8 @@ class Field(object): return value elif hasattr(self, 'model_field'): return self.model_field.value_to_string(self.obj) + elif hasattr(value, '__iter__') and not isinstance(value, (dict, basestring)): + return [self.to_native(item) for item in value] return smart_unicode(value) def attributes(self): diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 1e547b32e..8647ad425 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -16,20 +16,24 @@ class BaseView(views.APIView): """ serializer_class = None model_serializer_class = api_settings.MODEL_SERIALIZER - pagination_serializer_class = api_settings.PAGINATION_SERIALIZER - paginate_by = api_settings.PAGINATE_BY def get_serializer_context(self): + """ + Extra context provided to the serializer class. + """ return { 'request': self.request, - 'format': self.kwargs.get('format', None) + 'format': self.format, + 'view': self } - def get_serializer(self, data=None, files=None, instance=None, kwargs=None): - # TODO: add support for files - # TODO: add support for seperate serializer/deserializer + def get_serializer_class(self): + """ + Return the class to use for the serializer. + Use `self.serializer_class`, falling back to constructing a + model serializer class from `self.model_serializer_class` + """ serializer_class = self.serializer_class - kwargs = kwargs or {} if serializer_class is None: class DefaultSerializer(self.model_serializer_class): @@ -37,22 +41,38 @@ class BaseView(views.APIView): model = self.model serializer_class = DefaultSerializer - context = self.get_serializer_context() - return serializer_class(data, instance=instance, context=context, **kwargs) + return serializer_class - def get_pagination_serializer(self, page=None): - serializer_class = self.pagination_serializer_class + def get_serializer(self, data=None, files=None, instance=None): + # TODO: add support for files + # TODO: add support for seperate serializer/deserializer + serializer_class = self.get_serializer_class() context = self.get_serializer_context() - ret = serializer_class(instance=page, context=context) - ret.fields['results'] = self.get_serializer(kwargs={'source': 'object_list'}) - return ret + return serializer_class(data, instance=instance, context=context) class MultipleObjectBaseView(MultipleObjectMixin, BaseView): """ Base class for generic views onto a queryset. """ - pass + + pagination_serializer_class = api_settings.PAGINATION_SERIALIZER + paginate_by = api_settings.PAGINATE_BY + + def get_pagination_serializer_class(self): + """ + Return the class to use for the pagination serializer. + """ + class SerializerClass(self.pagination_serializer_class): + class Meta: + object_serializer_class = self.get_serializer_class() + + return SerializerClass + + def get_pagination_serializer(self, page=None): + pagination_serializer_class = self.get_pagination_serializer_class() + context = self.get_serializer_context() + return pagination_serializer_class(instance=page, context=context) class SingleObjectBaseView(SingleObjectMixin, BaseView): diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index 398e6f3d5..f8b1fd1a9 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -4,27 +4,64 @@ from rest_framework import serializers class NextPageField(serializers.Field): + """ + Field that returns a link to the next page in paginated results. + """ def to_native(self, value): if not value.has_next(): return None page = value.next_page_number() - request = self.context['request'] - return request.build_absolute_uri('?page=%d' % page) + request = self.context.get('request') + relative_url = '?page=%d' % page + if request: + return request.build_absolute_uri(relative_url) + return relative_url class PreviousPageField(serializers.Field): + """ + Field that returns a link to the previous page in paginated results. + """ def to_native(self, value): if not value.has_previous(): return None page = value.previous_page_number() - request = self.context['request'] - return request.build_absolute_uri('?page=%d' % page) + request = self.context.get('request') + relative_url = '?page=%d' % page + if request: + return request.build_absolute_uri('?page=%d' % page) + return relative_url -class PaginationSerializer(serializers.Serializer): - count = serializers.Field(source='paginator.count') - next = NextPageField(source='*') - previous = PreviousPageField(source='*') +class PaginationSerializerOptions(serializers.SerializerOptions): + """ + An object that stores the options that may be provided to a + pagination serializer by using the inner `Meta` class. + + Accessible on the instance as `serializer.opts`. + """ + def __init__(self, meta): + super(PaginationSerializerOptions, self).__init__(meta) + self.object_serializer_class = getattr(meta, 'object_serializer_class', + serializers.Field) + + +class BasePaginationSerializer(serializers.Serializer): + """ + A base class for pagination serializers to inherit from, + to make implementing custom serializers more easy. + """ + _options_class = PaginationSerializerOptions + _results_field = 'results' + + def __init__(self, *args, **kwargs): + """ + Override init to add in the object serializer field on-the-fly. + """ + super(BasePaginationSerializer, self).__init__(*args, **kwargs) + results_field = self._results_field + object_serializer = self.opts.object_serializer_class + self.fields[results_field] = object_serializer(source='object_list') def to_native(self, obj): """ @@ -32,3 +69,12 @@ class PaginationSerializer(serializers.Serializer): each in turn. """ return self.convert_object(obj) + + +class PaginationSerializer(BasePaginationSerializer): + """ + A default implementation of a pagination serializer. + """ + count = serializers.Field(source='paginator.count') + next = NextPageField(source='*') + previous = PreviousPageField(source='*') diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 9cbdb9de6..bb48e3817 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -70,7 +70,7 @@ class SerializerMetaclass(type): class SerializerOptions(object): """ - Meta class options for ModelSerializer + Meta class options for Serializer """ def __init__(self, meta): self.nested = getattr(meta, 'nested', False) diff --git a/rest_framework/tests/generics.py b/rest_framework/tests/generics.py index fee6e3a63..ec46b427f 100644 --- a/rest_framework/tests/generics.py +++ b/rest_framework/tests/generics.py @@ -13,6 +13,7 @@ class RootView(generics.RootAPIView): Example description for OPTIONS. """ model = BasicModel + paginate_by = None class InstanceView(generics.InstanceAPIView): diff --git a/rest_framework/tests/pagination.py b/rest_framework/tests/pagination.py index 4ddfc9157..9e424cc59 100644 --- a/rest_framework/tests/pagination.py +++ b/rest_framework/tests/pagination.py @@ -1,6 +1,7 @@ +from django.core.paginator import Paginator from django.test import TestCase from django.test.client import RequestFactory -from rest_framework import generics, status +from rest_framework import generics, status, pagination from rest_framework.tests.models import BasicModel factory = RequestFactory() @@ -14,7 +15,11 @@ class RootView(generics.RootAPIView): paginate_by = 10 -class TestPaginatedView(TestCase): +class IntegrationTestPagination(TestCase): + """ + Integration tests for paginated list views. + """ + def setUp(self): """ Create 26 BasicModel intances. @@ -55,3 +60,28 @@ class TestPaginatedView(TestCase): self.assertEquals(response.data['results'], self.data[20:]) self.assertEquals(response.data['next'], None) self.assertNotEquals(response.data['previous'], None) + + +class UnitTestPagination(TestCase): + """ + Unit tests for pagination of primative objects. + """ + + def setUp(self): + self.objects = [char * 3 for char in 'abcdefghijklmnopqrstuvwxyz'] + paginator = Paginator(self.objects, 10) + self.first_page = paginator.page(1) + self.last_page = paginator.page(3) + + def test_native_pagination(self): + serializer = pagination.PaginationSerializer(instance=self.first_page) + self.assertEquals(serializer.data['count'], 26) + self.assertEquals(serializer.data['next'], '?page=2') + self.assertEquals(serializer.data['previous'], None) + self.assertEquals(serializer.data['results'], self.objects[:10]) + + serializer = pagination.PaginationSerializer(instance=self.last_page) + self.assertEquals(serializer.data['count'], 26) + self.assertEquals(serializer.data['next'], None) + self.assertEquals(serializer.data['previous'], '?page=2') + self.assertEquals(serializer.data['results'], self.objects[20:]) From 8d1d99018725469061d5696a5552e7ebdb5cccc9 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Mon, 1 Oct 2012 16:17:01 +0100 Subject: [PATCH 04/15] Pagination docs --- Django | 0 docs/api-guide/pagination.md | 18 ++++++++++++------ docs/index.md | 2 ++ docs/static/css/default.css | 4 ++-- docs/template.html | 5 +++-- 5 files changed, 19 insertions(+), 10 deletions(-) create mode 100644 Django diff --git a/Django b/Django new file mode 100644 index 000000000..e69de29bb diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 0f0a32b5c..6211a0ac0 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -8,7 +8,7 @@ REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types. -## Examples +## Paginating basic data Let's start by taking a look at an example from the Django documentation. @@ -35,6 +35,8 @@ The `context` argument of the `PaginationSerializer` class may optionally includ We could now return that data in a `Response` object, and it would be rendered into the correct media type. +## Paginating QuerySets + Our first example worked because we were using primative objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself with. We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example. @@ -83,16 +85,20 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie pagination_serializer_class = CustomPaginationSerializer paginate_by = 10 +For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods. + ## Creating custom pagination serializers -Override `pagination.BasePaginationSerializer`, and set the fields that you want the serializer to return. +To create a custom pagination serializer class you should override `pagination.BasePaginationSerializer` and set the fields that you want the serializer to return. -For example. +For example, to nest a pair of links labelled 'prev' and 'next' you might use something like this. + + class LinksSerializer(serializers.Serializer): + next = pagination.NextURLField(source='*') + prev = pagination.PreviousURLField(source='*') class CustomPaginationSerializer(pagination.BasePaginationSerializer): - next = pagination.NextURLField() + links = LinksSerializer(source='*') # Takes the page object as the source total_results = serializers.Field(source='paginator.count') - [cite]: https://docs.djangoproject.com/en/dev/topics/pagination/ - diff --git a/docs/index.md b/docs/index.md index e7db5dbc7..92afbea8a 100644 --- a/docs/index.md +++ b/docs/index.md @@ -85,6 +85,7 @@ The API guide is your complete reference manual to all the functionality provide * [Authentication][authentication] * [Permissions][permissions] * [Throttling][throttling] +* [Pagination][pagination] * [Content negotiation][contentnegotiation] * [Format suffixes][formatsuffixes] * [Returning URLs][reverse] @@ -161,6 +162,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [authentication]: api-guide/authentication.md [permissions]: api-guide/permissions.md [throttling]: api-guide/throttling.md +[pagination]: api-guide/pagination.md [contentnegotiation]: api-guide/content-negotiation.md [formatsuffixes]: api-guide/format-suffixes.md [reverse]: api-guide/reverse.md diff --git a/docs/static/css/default.css b/docs/static/css/default.css index 213a700ed..49aac3a30 100644 --- a/docs/static/css/default.css +++ b/docs/static/css/default.css @@ -36,14 +36,14 @@ pre { } /* GitHub 'Star' badge */ -body.index #main-content iframe { +body.index-page #main-content iframe { float: right; margin-top: -12px; margin-right: -15px; } /* Travis CI badge */ -body.index #main-content p:first-of-type { +body.index-page #main-content p:first-of-type { float: right; margin-right: 8px; margin-top: -14px; diff --git a/docs/template.html b/docs/template.html index 4ac94f404..fbd30159a 100644 --- a/docs/template.html +++ b/docs/template.html @@ -16,7 +16,7 @@ - +