2013-11-17 22:26:41 +04:00
<!DOCTYPE html>
< html lang = "en" >
< head > < meta http-equiv = "Content-Type" content = "text/html; charset=UTF-8" >
< meta charset = "utf-8" >
2013-12-23 16:37:56 +04:00
< title > Pagination - Django REST framework< / title >
2014-08-02 18:28:53 +04:00
< link href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//img/favicon.ico" rel = "icon" type = "image/x-icon" >
< link rel = "canonical" href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/pagination.html" / >
2013-11-17 22:26:41 +04:00
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
2014-02-20 18:55:10 +04:00
< meta name = "description" content = "Django, API, REST, Pagination, Custom pagination serializers, Third party packages" >
2013-11-17 22:26:41 +04:00
< meta name = "author" content = "Tom Christie" >
<!-- Le styles -->
2014-08-02 18:28:53 +04:00
< link href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//css/prettify.css" rel = "stylesheet" >
< link href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//css/bootstrap.css" rel = "stylesheet" >
< link href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//css/bootstrap-responsive.css" rel = "stylesheet" >
< link href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//css/default.css" rel = "stylesheet" >
2013-11-17 22:26:41 +04:00
<!-- Le HTML5 shim, for IE6 - 8 support of HTML5 elements -->
<!-- [if lt IE 9]>
< script src = "http://html5shim.googlecode.com/svn/trunk/html5.js" > < / script >
<![endif]-->
< script type = "text/javascript" >
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18852272-2']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
< / script >
2014-07-15 18:02:49 +04:00
< style >
span.fusion-wrap a {
display: block;
margin-top: 10px;
color: black;
}
a.fusion-poweredby {
display: block;
margin-top: 10px;
}
@media (max-width: 767px) {
div.promo {display: none;}
}
< / style >
2013-11-17 22:26:41 +04:00
< / head >
< body onload = "prettyPrint()" class = "pagination-page" >
< div class = "wrapper" >
< div class = "navbar navbar-inverse navbar-fixed-top" >
< div class = "navbar-inner" >
< div class = "container-fluid" >
< a class = "repo-link btn btn-primary btn-small" href = "https://github.com/tomchristie/django-rest-framework/tree/master" > GitHub< / a >
2014-08-02 18:28:53 +04:00
< a class = "repo-link btn btn-inverse btn-small " href = "../api-guide/content-negotiation.html" > Next < i class = "icon-arrow-right icon-white" > < / i > < / a >
< a class = "repo-link btn btn-inverse btn-small " href = "../api-guide/filtering.html" > < i class = "icon-arrow-left icon-white" > < / i > Previous< / a >
2013-11-17 22:26:41 +04:00
< a class = "repo-link btn btn-inverse btn-small" href = "#searchModal" data-toggle = "modal" > < i class = "icon-search icon-white" > < / i > Search< / a >
< a class = "btn btn-navbar" data-toggle = "collapse" data-target = ".nav-collapse" >
< span class = "icon-bar" > < / span >
< span class = "icon-bar" > < / span >
< span class = "icon-bar" > < / span >
< / a >
2014-08-02 18:28:53 +04:00
< a class = "brand" href = "file:///Users/tomchristie/GitHub/django-rest-framework/html/index.html" > Django REST framework< / a >
2013-11-17 22:26:41 +04:00
< div class = "nav-collapse collapse" >
< ul class = "nav" >
2014-08-02 18:28:53 +04:00
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html/index.html" > Home< / a > < / li >
2013-11-17 22:26:41 +04:00
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Tutorial < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
2014-08-02 18:28:53 +04:00
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/quickstart.html" > Quickstart< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/1-serialization.html" > 1 - Serialization< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/2-requests-and-responses.html" > 2 - Requests and responses< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/3-class-based-views.html" > 3 - Class based views< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/4-authentication-and-permissions.html" > 4 - Authentication and permissions< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/5-relationships-and-hyperlinked-apis.html" > 5 - Relationships and hyperlinked APIs< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//tutorial/6-viewsets-and-routers.html" > 6 - Viewsets and routers< / a > < / li >
2013-11-17 22:26:41 +04:00
< / ul >
< / li >
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > API Guide < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
2014-08-02 18:28:53 +04:00
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/requests.html" > Requests< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/responses.html" > Responses< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/views.html" > Views< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/generic-views.html" > Generic views< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/viewsets.html" > Viewsets< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/routers.html" > Routers< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/parsers.html" > Parsers< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/renderers.html" > Renderers< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/serializers.html" > Serializers< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/fields.html" > Serializer fields< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/relations.html" > Serializer relations< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/authentication.html" > Authentication< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/permissions.html" > Permissions< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/throttling.html" > Throttling< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/filtering.html" > Filtering< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/pagination.html" > Pagination< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/content-negotiation.html" > Content negotiation< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/format-suffixes.html" > Format suffixes< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/reverse.html" > Returning URLs< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/exceptions.html" > Exceptions< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/status-codes.html" > Status codes< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/testing.html" > Testing< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//api-guide/settings.html" > Settings< / a > < / li >
2013-11-17 22:26:41 +04:00
< / ul >
< / li >
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Topics < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
2014-08-02 18:28:53 +04:00
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/documenting-your-api.html" > Documenting your API< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/ajax-csrf-cors.html" > AJAX, CSRF & CORS< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/browser-enhancements.html" > Browser enhancements< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/browsable-api.html" > The Browsable API< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/rest-hypermedia-hateoas.html" > REST, Hypermedia & HATEOAS< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/contributing.html" > Contributing to REST framework< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/rest-framework-2-announcement.html" > 2.0 Announcement< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/2.2-announcement.html" > 2.2 Announcement< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/2.3-announcement.html" > 2.3 Announcement< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/kickstarter-announcement.html" > Kickstarter Announcement< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/release-notes.html" > Release Notes< / a > < / li >
< li > < a href = "file:///Users/tomchristie/GitHub/django-rest-framework/html//topics/credits.html" > Credits< / a > < / li >
2013-11-17 22:26:41 +04:00
< / ul >
< / li >
< / ul >
< ul class = "nav pull-right" >
<!-- TODO
< li class = "dropdown" >
< a href = "#" class = "dropdown-toggle" data-toggle = "dropdown" > Version: 2.0.0 < b class = "caret" > < / b > < / a >
< ul class = "dropdown-menu" >
< li > < a href = "#" > Trunk< / a > < / li >
< li > < a href = "#" > 2.0.0< / a > < / li >
< / ul >
< / li >
-->
< / ul >
< / div > <!-- /.nav - collapse -->
< / div >
< / div >
< / div >
< div class = "body-content" >
< div class = "container-fluid" >
<!-- Search Modal -->
< div id = "searchModal" class = "modal hide fade" tabindex = "-1" role = "dialog" aria-labelledby = "myModalLabel" aria-hidden = "true" >
< div class = "modal-header" >
< button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true" > × < / button >
< h3 id = "myModalLabel" > Documentation search< / h3 >
< / div >
< div class = "modal-body" >
<!-- Custom google search -->
< script >
(function() {
var cx = '015016005043623903336:rxraeohqk6w';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
'//www.google.com/cse/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
< / script >
< gcse:search > < / gcse:search >
< / div >
< div class = "modal-footer" >
< button class = "btn" data-dismiss = "modal" aria-hidden = "true" > Close< / button >
< / div >
< / div >
< div class = "row-fluid" >
< div class = "span3" >
<!-- TODO
< p style = "margin-top: -12px" >
< a class = "btn btn-mini btn-primary" style = "width: 60px" > « previous< / a >
< a class = "btn btn-mini btn-primary" style = "float: right; margin-right: 8px; width: 60px;" > next » < / a >
< / p >
-->
< div id = "table-of-contents" >
< ul class = "nav nav-list side-nav well sidebar-nav-fixed" >
< li class = "main" > < a href = "#pagination" > Pagination< / a > < / li >
< li > < a href = "#paginating-basic-data" > Paginating basic data< / a > < / li >
< li > < a href = "#paginating-querysets" > Paginating QuerySets< / a > < / li >
< li > < a href = "#pagination-in-the-generic-views" > Pagination in the generic views< / a > < / li >
< li class = "main" > < a href = "#custom-pagination-serializers" > Custom pagination serializers< / a > < / li >
< li > < a href = "#example" > Example< / a > < / li >
< li > < a href = "#using-your-custom-pagination-serializer" > Using your custom pagination serializer< / a > < / li >
2014-02-20 18:55:10 +04:00
< li class = "main" > < a href = "#third-party-packages" > Third party packages< / a > < / li >
< li > < a href = "#drf-extensions" > DRF-extensions< / a > < / li >
2013-11-17 22:26:41 +04:00
2014-07-15 18:02:49 +04:00
< div class = "promo" >
< / div >
2014-01-03 17:26:35 +04:00
< / ul >
2013-11-17 22:26:41 +04:00
< / div >
< / div >
< div id = "main-content" class = "span9" >
< p > < a class = "github" href = "https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/pagination.py" > < span class = "label label-info" > pagination.py< / span > < / a > < / p >
< h1 id = "pagination" > Pagination< / h1 >
< blockquote >
< p > Django provides a few classes that help you manage paginated data – that is, data that’ s split across several pages, with “Previous/Next” links.< / p >
< p > — < a href = "https://docs.djangoproject.com/en/dev/topics/pagination/" > Django documentation< / a > < / p >
< / blockquote >
< p > REST framework includes a < code > PaginationSerializer< / code > class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types. < / p >
< h2 id = "paginating-basic-data" > Paginating basic data< / h2 >
< p > Let's start by taking a look at an example from the Django documentation.< / p >
< pre class = "prettyprint lang-py" > < code > from django.core.paginator import Paginator
objects = ['john', 'paul', 'george', 'ringo']
paginator = Paginator(objects, 2)
page = paginator.page(1)
page.object_list
# ['john', 'paul']
< / code > < / pre >
< p > 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.< / p >
< pre class = "prettyprint lang-py" > < code > from rest_framework.pagination import PaginationSerializer
serializer = PaginationSerializer(instance=page)
serializer.data
# {'count': 4, 'next': '?page=2', 'previous': None, 'results': [u'john', u'paul']}
< / code > < / pre >
< p > The < code > context< / code > argument of the < code > PaginationSerializer< / code > 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.< / p >
< pre class = "prettyprint lang-py" > < code > 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']}
< / code > < / pre >
< p > We could now return that data in a < code > Response< / code > object, and it would be rendered into the correct media type.< / p >
< h2 id = "paginating-querysets" > Paginating QuerySets< / h2 >
< p > Our first example worked because we were using primitive 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.< / p >
< p > We can do this using the < code > object_serializer_class< / code > attribute on the inner < code > Meta< / code > class of the pagination serializer. For example.< / p >
< pre class = "prettyprint lang-py" > < code > 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
< / code > < / pre >
< p > We could now use our pagination serializer in a view like this.< / p >
< pre class = "prettyprint lang-py" > < code > @api_view('GET')
def user_list(request):
queryset = User.objects.all()
paginator = Paginator(queryset, 20)
page = request.QUERY_PARAMS.get('page')
try:
users = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
users = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999),
# deliver last page of results.
users = paginator.page(paginator.num_pages)
serializer_context = {'request': request}
serializer = PaginatedUserSerializer(users,
context=serializer_context)
return Response(serializer.data)
< / code > < / pre >
< h2 id = "pagination-in-the-generic-views" > Pagination in the generic views< / h2 >
< p > The generic class based views < code > ListAPIView< / code > and < code > ListCreateAPIView< / code > 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, by allowing clients to override the page size using a query parameter, or by turning pagination off completely.< / p >
< p > The default pagination style may be set globally, using the < code > DEFAULT_PAGINATION_SERIALIZER_CLASS< / code > , < code > PAGINATE_BY< / code > , < code > PAGINATE_BY_PARAM< / code > , and < code > MAX_PAGINATE_BY< / code > settings. For example.< / p >
< pre class = "prettyprint lang-py" > < code > REST_FRAMEWORK = {
'PAGINATE_BY': 10, # Default to 10
'PAGINATE_BY_PARAM': 'page_size', # Allow client to override, using `?page_size=xxx`.
'MAX_PAGINATE_BY': 100 # Maximum limit allowed when using `?page_size=xxx`.
}
< / code > < / pre >
< p > You can also set the pagination style on a per-view basis, using the < code > ListAPIView< / code > generic class-based view.< / p >
< pre class = "prettyprint lang-py" > < code > class PaginatedListView(ListAPIView):
queryset = ExampleModel.objects.all()
serializer_class = ExampleModelSerializer
paginate_by = 10
paginate_by_param = 'page_size'
max_paginate_by = 100
< / code > < / pre >
2014-06-12 15:22:09 +04:00
< p > Note that using a < code > paginate_by< / code > value of < code > None< / code > will turn off pagination for the view.
Note if you use the < code > PAGINATE_BY_PARAM< / code > settings, you also have to set the < code > paginate_by_param< / code > attribute in your view to < code > None< / code > in order to turn off pagination for those requests that contain the < code > paginate_by_param< / code > parameter.< / p >
2013-11-17 22:26:41 +04:00
< p > For more complex requirements such as serialization that differs depending on the requested media type you can override the < code > .get_paginate_by()< / code > and < code > .get_pagination_serializer_class()< / code > methods.< / p >
< hr / >
< h1 id = "custom-pagination-serializers" > Custom pagination serializers< / h1 >
< p > To create a custom pagination serializer class you should override < code > pagination.BasePaginationSerializer< / code > and set the fields that you want the serializer to return.< / p >
< p > You can also override the name used for the object list field, by setting the < code > results_field< / code > attribute, which defaults to < code > 'results'< / code > .< / p >
< h2 id = "example" > Example< / h2 >
< p > For example, to nest a pair of links labelled 'prev' and 'next', and set the name for the results field to 'objects', you might use something like this.< / p >
< pre class = "prettyprint lang-py" > < code > from rest_framework import pagination
from rest_framework import serializers
class LinksSerializer(serializers.Serializer):
next = pagination.NextPageField(source='*')
prev = pagination.PreviousPageField(source='*')
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
links = LinksSerializer(source='*') # Takes the page object as the source
total_results = serializers.Field(source='paginator.count')
results_field = 'objects'
< / code > < / pre >
< h2 id = "using-your-custom-pagination-serializer" > Using your custom pagination serializer< / h2 >
< p > To have your custom pagination serializer be used by default, use the < code > DEFAULT_PAGINATION_SERIALIZER_CLASS< / code > setting:< / p >
< pre class = "prettyprint lang-py" > < code > REST_FRAMEWORK = {
'DEFAULT_PAGINATION_SERIALIZER_CLASS':
'example_app.pagination.CustomPaginationSerializer',
}
< / code > < / pre >
< p > Alternatively, to set your custom pagination serializer on a per-view basis, use the < code > pagination_serializer_class< / code > attribute on a generic class based view:< / p >
< pre class = "prettyprint lang-py" > < code > class PaginatedListView(generics.ListAPIView):
model = ExampleModel
pagination_serializer_class = CustomPaginationSerializer
paginate_by = 10
< / code > < / pre >
2014-02-20 18:55:10 +04:00
< h1 id = "third-party-packages" > Third party packages< / h1 >
< p > The following third party packages are also available.< / p >
< h2 id = "drf-extensions" > DRF-extensions< / h2 >
< p > The < a href = "http://chibisov.github.io/drf-extensions/docs/" > < code > DRF-extensions< / code > package< / a > includes a < a href = "http://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin" > < code > PaginateByMaxMixin< / code > mixin class< / a > that allows your API clients to specify < code > ?page_size=max< / code > to obtain the maximum allowed page size.< / p >
2013-11-17 22:26:41 +04:00
< / div > <!-- /span -->
< / div > <!-- /row -->
< / div > <!-- /.fluid - container -->
< / div > <!-- /.body content -->
< div id = "push" > < / div >
< / div > <!-- /.wrapper -->
< footer class = "span12" >
< p > Sponsored by < a href = "http://dabapps.com/" > DabApps< / a > .< / a > < / p >
< / footer >
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
2014-08-02 18:28:53 +04:00
< script src = "file:///Users/tomchristie/GitHub/django-rest-framework/html//js/jquery-1.8.1-min.js" > < / script >
< script src = "file:///Users/tomchristie/GitHub/django-rest-framework/html//js/prettify-1.0.js" > < / script >
< script src = "file:///Users/tomchristie/GitHub/django-rest-framework/html//js/bootstrap-2.1.1-min.js" > < / script >
2014-07-15 18:02:49 +04:00
2013-11-17 22:26:41 +04:00
< script >
//$('.side-nav').scrollspy()
var shiftWindow = function() { scrollBy(0, -50) };
if (location.hash) shiftWindow();
window.addEventListener("hashchange", shiftWindow);
$('.dropdown-menu').on('click touchstart', function(event) {
event.stopPropagation();
});
// Dynamically force sidenav to no higher than browser window
$('.side-nav').css('max-height', window.innerHeight - 130);
$(function(){
$(window).resize(function(){
$('.side-nav').css('max-height', window.innerHeight - 130);
});
});
< / script >
< / body > < / html >