django-rest-framework/api-guide/pagination.html
2012-10-19 20:00:35 +01:00

257 lines
16 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Django REST framework</title>
<link href="http://tomchristie.github.com/django-rest-framework/img/favicon.ico" rel="icon" type="image/x-icon">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="http://tomchristie.github.com/django-rest-framework/css/prettify.css" rel="stylesheet">
<link href="http://tomchristie.github.com/django-rest-framework/css/bootstrap.css" rel="stylesheet">
<link href="http://tomchristie.github.com/django-rest-framework/css/bootstrap-responsive.css" rel="stylesheet">
<link href="http://tomchristie.github.com/django-rest-framework/css/default.css" rel="stylesheet">
<!-- 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]-->
<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/restframework2">GitHub</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>
<a class="brand" href="http://tomchristie.github.com/django-rest-framework">Django REST framework</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li><a href="http://tomchristie.github.com/django-rest-framework">Home</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/quickstart">Quickstart</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/1-serialization">1 - Serialization</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/2-requests-and-responses">2 - Requests and responses</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/3-class-based-views">3 - Class based views</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/4-authentication-permissions-and-throttling">4 - Authentication, permissions and throttling</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li>
<!-- <li><a href="http://tomchristie.github.com/django-rest-framework/tutorial/6-resource-orientated-projects">6 - Resource orientated projects</a></li> -->
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/requests">Requests</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/responses">Responses</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/views">Views</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/generic-views">Generic views</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/parsers">Parsers</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/renderers">Renderers</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/serializers">Serializers</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/fields">Serializer fields</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/authentication">Authentication</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/permissions">Permissions</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/throttling">Throttling</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/pagination">Pagination</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/content-negotiation">Content negotiation</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/format-suffixes">Format suffixes</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/reverse">Returning URLs</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/exceptions">Exceptions</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/status-codes">Status codes</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/api-guide/settings">Settings</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/csrf">Working with AJAX and CSRF</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/browser-enhancements">Browser enhancements</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/browsable-api">The Browsable API</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/contributing">Contributing to REST framework</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/migration">2.0 Migration Guide</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/release-notes">Release Notes</a></li>
<li><a href="http://tomchristie.github.com/django-rest-framework/topics/credits">Credits</a></li>
</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">
<div class="row-fluid">
<div class="span3">
<!-- TODO
<p style="margin-top: -12px">
<a class="btn btn-mini btn-primary" style="width: 60px">&laquo; previous</a>
<a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next &raquo;</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>
</ul>
</div>
</div>
<div id="main-content" class="span9">
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/blob/restframework2/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 thats split across several pages, with “Previous/Next” links.</p>
<p>&mdash; <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 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.</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(instance=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, or by turning pagination off completely.</p>
<p>The default pagination style may be set globally, using the <code>PAGINATION_SERIALIZER</code> and <code>PAGINATE_BY</code> settings. For example.</p>
<pre class="prettyprint lang-py"><code>REST_FRAMEWORK = {
'PAGINATION_SERIALIZER': (
'example_app.pagination.CustomPaginationSerializer',
),
'PAGINATE_BY': 10
}
</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):
model = ExampleModel
pagination_serializer_class = CustomPaginationSerializer
paginate_by = 10
</code></pre>
<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>class LinksSerializer(serializers.Serializer):
next = pagination.NextURLField(source='*')
prev = pagination.PreviousURLField(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>
</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 -->
<script src="http://tomchristie.github.com/django-rest-framework/js/jquery-1.8.1-min.js"></script>
<script src="http://tomchristie.github.com/django-rest-framework/js/prettify-1.0.js"></script>
<script src="http://tomchristie.github.com/django-rest-framework/js/bootstrap-2.1.1-min.js"></script>
<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();
});
</script>
</body></html>