mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-23 01:57:00 +03:00
520 lines
36 KiB
HTML
520 lines
36 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="en">
|
||
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
|
||
<meta charset="utf-8">
|
||
<title>Generic views - Django REST framework</title>
|
||
<link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
|
||
<link rel="canonical" href="http://www.django-rest-framework.org/api-guide/generic-views"/>
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<meta name="description" content="Django, API, REST, Generic views, API Reference, Mixins, Concrete View Classes, Customizing the generic views, Third party packages">
|
||
<meta name="author" content="Tom Christie">
|
||
|
||
<!-- Le styles -->
|
||
<link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet">
|
||
<link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
|
||
<link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
|
||
<link href="http://www.django-rest-framework.org/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]-->
|
||
|
||
<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>
|
||
<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>
|
||
</head>
|
||
<body onload="prettyPrint()" class="generic-views-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>
|
||
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/viewsets">Next <i class="icon-arrow-right icon-white"></i></a>
|
||
<a class="repo-link btn btn-inverse btn-small " href="../api-guide/views"><i class="icon-arrow-left icon-white"></i> Previous</a>
|
||
<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>
|
||
<a class="brand" href="http://www.django-rest-framework.org">Django REST framework</a>
|
||
<div class="nav-collapse collapse">
|
||
<ul class="nav">
|
||
<li><a href="http://www.django-rest-framework.org">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://www.django-rest-framework.org/tutorial/quickstart">Quickstart</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/tutorial/1-serialization">1 - Serialization</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/tutorial/2-requests-and-responses">2 - Requests and responses</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/tutorial/3-class-based-views">3 - Class based views</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions">4 - Authentication and permissions</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis">5 - Relationships and hyperlinked APIs</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers">6 - Viewsets and routers</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://www.django-rest-framework.org/api-guide/requests">Requests</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/responses">Responses</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/views">Views</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/generic-views">Generic views</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/viewsets">Viewsets</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/routers">Routers</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/parsers">Parsers</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/renderers">Renderers</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/serializers">Serializers</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/fields">Serializer fields</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/relations">Serializer relations</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/authentication">Authentication</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/permissions">Permissions</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/throttling">Throttling</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/filtering">Filtering</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/pagination">Pagination</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/content-negotiation">Content negotiation</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/format-suffixes">Format suffixes</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/reverse">Returning URLs</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/exceptions">Exceptions</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/status-codes">Status codes</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/api-guide/testing">Testing</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/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://www.django-rest-framework.org/topics/documenting-your-api">Documenting your API</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/ajax-csrf-cors">AJAX, CSRF & CORS</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/browser-enhancements">Browser enhancements</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/browsable-api">The Browsable API</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/rest-hypermedia-hateoas">REST, Hypermedia & HATEOAS</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/contributing">Contributing to REST framework</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/rest-framework-2-announcement">2.0 Announcement</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/2.2-announcement">2.2 Announcement</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/2.3-announcement">2.3 Announcement</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/kickstarter-announcement">Kickstarter Announcement</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/topics/release-notes">Release Notes</a></li>
|
||
<li><a href="http://www.django-rest-framework.org/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">
|
||
|
||
<!-- 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="#generic-views">Generic views</a></li>
|
||
<li><a href="#examples">Examples</a></li>
|
||
<li class="main"><a href="#api-reference">API Reference</a></li>
|
||
<li><a href="#genericapiview">GenericAPIView</a></li>
|
||
<li class="main"><a href="#mixins">Mixins</a></li>
|
||
<li><a href="#listmodelmixin">ListModelMixin</a></li>
|
||
<li><a href="#createmodelmixin">CreateModelMixin</a></li>
|
||
<li><a href="#retrievemodelmixin">RetrieveModelMixin</a></li>
|
||
<li><a href="#updatemodelmixin">UpdateModelMixin</a></li>
|
||
<li><a href="#destroymodelmixin">DestroyModelMixin</a></li>
|
||
<li class="main"><a href="#concrete-view-classes">Concrete View Classes</a></li>
|
||
<li><a href="#createapiview">CreateAPIView</a></li>
|
||
<li><a href="#listapiview">ListAPIView</a></li>
|
||
<li><a href="#retrieveapiview">RetrieveAPIView</a></li>
|
||
<li><a href="#destroyapiview">DestroyAPIView</a></li>
|
||
<li><a href="#updateapiview">UpdateAPIView</a></li>
|
||
<li><a href="#listcreateapiview">ListCreateAPIView</a></li>
|
||
<li><a href="#retrieveupdateapiview">RetrieveUpdateAPIView</a></li>
|
||
<li><a href="#retrievedestroyapiview">RetrieveDestroyAPIView</a></li>
|
||
<li><a href="#retrieveupdatedestroyapiview">RetrieveUpdateDestroyAPIView</a></li>
|
||
<li class="main"><a href="#customizing-the-generic-views">Customizing the generic views</a></li>
|
||
<li><a href="#creating-custom-mixins">Creating custom mixins</a></li>
|
||
<li><a href="#creating-custom-base-classes">Creating custom base classes</a></li>
|
||
<li class="main"><a href="#third-party-packages">Third party packages</a></li>
|
||
<li><a href="#django-rest-framework-bulk">Django REST Framework bulk</a></li>
|
||
|
||
<div class="promo">
|
||
|
||
</div>
|
||
</ul>
|
||
|
||
</div>
|
||
</div>
|
||
|
||
<div id="main-content" class="span9">
|
||
<p><a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/mixins.py"><span class="label label-info">mixins.py</span></a>
|
||
<a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/generics.py"><span class="label label-info">generics.py</span></a></p>
|
||
<h1 id="generic-views">Generic views</h1>
|
||
<blockquote>
|
||
<p>Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.</p>
|
||
<p>— <a href="https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views">Django Documentation</a></p>
|
||
</blockquote>
|
||
<p>One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.</p>
|
||
<p>The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.</p>
|
||
<p>If the generic views don't suit the needs of your API, you can drop down to using the regular <code>APIView</code> class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.</p>
|
||
<h2 id="examples">Examples</h2>
|
||
<p>Typically when using the generic views, you'll override the view, and set several class attributes.</p>
|
||
<pre class="prettyprint lang-py"><code>from django.contrib.auth.models import User
|
||
from myapp.serializers import UserSerializer
|
||
from rest_framework import generics
|
||
from rest_framework.permissions import IsAdminUser
|
||
|
||
class UserList(generics.ListCreateAPIView):
|
||
queryset = User.objects.all()
|
||
serializer_class = UserSerializer
|
||
permission_classes = (IsAdminUser,)
|
||
paginate_by = 100
|
||
</code></pre>
|
||
<p>For more complex cases you might also want to override various methods on the view class. For example.</p>
|
||
<pre class="prettyprint lang-py"><code>class UserList(generics.ListCreateAPIView):
|
||
queryset = User.objects.all()
|
||
serializer_class = UserSerializer
|
||
permission_classes = (IsAdminUser,)
|
||
|
||
def get_paginate_by(self):
|
||
"""
|
||
Use smaller pagination for HTML representations.
|
||
"""
|
||
if self.request.accepted_renderer.format == 'html':
|
||
return 20
|
||
return 100
|
||
|
||
def list(self, request):
|
||
# Note the use of `get_queryset()` instead of `self.queryset`
|
||
queryset = self.get_queryset()
|
||
serializer = UserSerializer(queryset, many=True)
|
||
return Response(serializer.data)
|
||
</code></pre>
|
||
<p>For very simple cases you might want to pass through any class attributes using the <code>.as_view()</code> method. For example, your URLconf might include something like the following entry:</p>
|
||
<pre class="prettyprint lang-py"><code>url(r'^/users/', ListCreateAPIView.as_view(model=User), name='user-list')
|
||
</code></pre>
|
||
<hr />
|
||
<h1 id="api-reference">API Reference</h1>
|
||
<h2 id="genericapiview">GenericAPIView</h2>
|
||
<p>This class extends REST framework's <code>APIView</code> class, adding commonly required behavior for standard list and detail views.</p>
|
||
<p>Each of the concrete generic views provided is built by combining <code>GenericAPIView</code>, with one or more mixin classes.</p>
|
||
<h3 id="attributes">Attributes</h3>
|
||
<p><strong>Basic settings</strong>:</p>
|
||
<p>The following attributes control the basic view behavior.</p>
|
||
<ul>
|
||
<li><code>queryset</code> - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the <code>get_queryset()</code> method. If you are overriding a view method, it is important that you call <code>get_queryset()</code> instead of accessing this property directly, as <code>queryset</code> will get evaluated once, and those results will be cached for all subsequent requests.</li>
|
||
<li><code>serializer_class</code> - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the <code>get_serializer_class()</code> method.</li>
|
||
<li><code>lookup_field</code> - The model field that should be used to for performing object lookup of individual model instances. Defaults to <code>'pk'</code>. Note that when using hyperlinked APIs you'll need to ensure that <em>both</em> the API views <em>and</em> the serializer classes set the lookup fields if you need to use a custom value.</li>
|
||
<li><code>lookup_url_kwarg</code> - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as <code>lookup_field</code>.</li>
|
||
</ul>
|
||
<p><strong>Shortcuts</strong>:</p>
|
||
<ul>
|
||
<li><code>model</code> - This shortcut may be used instead of setting either (or both) of the <code>queryset</code>/<code>serializer_class</code> attributes, although using the explicit style is generally preferred. If used instead of <code>serializer_class</code>, then <code>DEFAULT_MODEL_SERIALIZER_CLASS</code> setting will determine the base serializer class. Note that <code>model</code> is only ever used for generating a default queryset or serializer class - the <code>queryset</code> and <code>serializer_class</code> attributes are always preferred if provided.</li>
|
||
</ul>
|
||
<p><strong>Pagination</strong>:</p>
|
||
<p>The following attributes are used to control pagination when used with list views.</p>
|
||
<ul>
|
||
<li><code>paginate_by</code> - The size of pages to use with paginated data. If set to <code>None</code> then pagination is turned off. If unset this uses the same value as the <code>PAGINATE_BY</code> setting, which defaults to <code>None</code>.</li>
|
||
<li><code>paginate_by_param</code> - The name of a query parameter, which can be used by the client to override the default page size to use for pagination. If unset this uses the same value as the <code>PAGINATE_BY_PARAM</code> setting, which defaults to <code>None</code>.</li>
|
||
<li><code>pagination_serializer_class</code> - The pagination serializer class to use when determining the style of paginated responses. Defaults to the same value as the <code>DEFAULT_PAGINATION_SERIALIZER_CLASS</code> setting.</li>
|
||
<li><code>page_kwarg</code> - The name of a URL kwarg or URL query parameter which can be used by the client to control which page is requested. Defaults to <code>'page'</code>.</li>
|
||
</ul>
|
||
<p><strong>Filtering</strong>:</p>
|
||
<ul>
|
||
<li><code>filter_backends</code> - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the <code>DEFAULT_FILTER_BACKENDS</code> setting.</li>
|
||
</ul>
|
||
<h3 id="methods">Methods</h3>
|
||
<p><strong>Base methods</strong>:</p>
|
||
<h4 id="get_querysetself"><code>get_queryset(self)</code></h4>
|
||
<p>Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the <code>queryset</code> attribute, or the default queryset for the model if the <code>model</code> shortcut is being used.</p>
|
||
<p>This method should always be used rather than accessing <code>self.queryset</code> directly, as <code>self.queryset</code> gets evaluated only once, and those results are cached for all subsequent requests.</p>
|
||
<p>May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request.</p>
|
||
<p>For example:</p>
|
||
<pre class="prettyprint lang-py"><code>def get_queryset(self):
|
||
user = self.request.user
|
||
return user.accounts.all()
|
||
</code></pre>
|
||
<h4 id="get_objectself"><code>get_object(self)</code></h4>
|
||
<p>Returns an object instance that should be used for detail views. Defaults to using the <code>lookup_field</code> parameter to filter the base queryset.</p>
|
||
<p>May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg.</p>
|
||
<p>For example:</p>
|
||
<pre class="prettyprint lang-py"><code>def get_object(self):
|
||
queryset = self.get_queryset()
|
||
filter = {}
|
||
for field in self.multiple_lookup_fields:
|
||
filter[field] = self.kwargs[field]
|
||
|
||
obj = get_object_or_404(queryset, **filter)
|
||
self.check_object_permissions(self.request, obj)
|
||
return obj
|
||
</code></pre>
|
||
<p>Note that if your API doesn't include any object level permissions, you may optionally exclude the <code>self.check_object_permissions</code>, and simply return the object from the <code>get_object_or_404</code> lookup.</p>
|
||
<h4 id="get_filter_backendsself"><code>get_filter_backends(self)</code></h4>
|
||
<p>Returns the classes that should be used to filter the queryset. Defaults to returning the <code>filter_backends</code> attribute.</p>
|
||
<p>May be overridden to provide more complex behavior with filters, such as using different (or even exlusive) lists of filter_backends depending on different criteria.</p>
|
||
<p>For example:</p>
|
||
<pre class="prettyprint lang-py"><code>def get_filter_backends(self):
|
||
if "geo_route" in self.request.QUERY_PARAMS:
|
||
return (GeoRouteFilter, CategoryFilter)
|
||
elif "geo_point" in self.request.QUERY_PARAMS:
|
||
return (GeoPointFilter, CategoryFilter)
|
||
|
||
return (CategoryFilter,)
|
||
</code></pre>
|
||
<h4 id="get_serializer_classself"><code>get_serializer_class(self)</code></h4>
|
||
<p>Returns the class that should be used for the serializer. Defaults to returning the <code>serializer_class</code> attribute, or dynamically generating a serializer class if the <code>model</code> shortcut is being used.</p>
|
||
<p>May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.</p>
|
||
<p>For example:</p>
|
||
<pre class="prettyprint lang-py"><code>def get_serializer_class(self):
|
||
if self.request.user.is_staff:
|
||
return FullAccountSerializer
|
||
return BasicAccountSerializer
|
||
</code></pre>
|
||
<h4 id="get_paginate_byself"><code>get_paginate_by(self)</code></h4>
|
||
<p>Returns the page size to use with pagination. By default this uses the <code>paginate_by</code> attribute, and may be overridden by the client if the <code>paginate_by_param</code> attribute is set.</p>
|
||
<p>You may want to override this method to provide more complex behavior, such as modifying page sizes based on the media type of the response.</p>
|
||
<p>For example:</p>
|
||
<pre class="prettyprint lang-py"><code>def get_paginate_by(self):
|
||
if self.request.accepted_renderer.format == 'html':
|
||
return 20
|
||
return 100
|
||
</code></pre>
|
||
<p><strong>Save / deletion hooks</strong>:</p>
|
||
<p>The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by <code>GenericAPIView</code>, but they are overridden and used by some of the mixin classes.</p>
|
||
<ul>
|
||
<li><code>pre_save(self, obj)</code> - A hook that is called before saving an object.</li>
|
||
<li><code>post_save(self, obj, created=False)</code> - A hook that is called after saving an object.</li>
|
||
<li><code>pre_delete(self, obj)</code> - A hook that is called before deleting an object.</li>
|
||
<li><code>post_delete(self, obj)</code> - A hook that is called after deleting an object.</li>
|
||
</ul>
|
||
<p>The <code>pre_save</code> method in particular is a useful hook for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.</p>
|
||
<pre class="prettyprint lang-py"><code>def pre_save(self, obj):
|
||
"""
|
||
Set the object's owner, based on the incoming request.
|
||
"""
|
||
obj.owner = self.request.user
|
||
</code></pre>
|
||
<p>Remember that the <code>pre_save()</code> method is not called by <code>GenericAPIView</code> itself, but it is called by <code>create()</code> and <code>update()</code> methods on the <code>CreateModelMixin</code> and <code>UpdateModelMixin</code> classes.</p>
|
||
<p><strong>Other methods</strong>:</p>
|
||
<p>You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using <code>GenericAPIView</code>.</p>
|
||
<ul>
|
||
<li><code>get_serializer_context(self)</code> - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including <code>'request'</code>, <code>'view'</code> and <code>'format'</code> keys.</li>
|
||
<li><code>get_serializer(self, instance=None, data=None, files=None, many=False, partial=False, allow_add_remove=False)</code> - Returns a serializer instance.</li>
|
||
<li><code>get_pagination_serializer(self, page)</code> - Returns a serializer instance to use with paginated data.</li>
|
||
<li><code>paginate_queryset(self, queryset)</code> - Paginate a queryset if required, either returning a page object, or <code>None</code> if pagination is not configured for this view.</li>
|
||
<li><code>filter_queryset(self, queryset)</code> - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset.</li>
|
||
</ul>
|
||
<hr />
|
||
<h1 id="mixins">Mixins</h1>
|
||
<p>The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as <code>.get()</code> and <code>.post()</code>, directly. This allows for more flexible composition of behavior.</p>
|
||
<h2 id="listmodelmixin">ListModelMixin</h2>
|
||
<p>Provides a <code>.list(request, *args, **kwargs)</code> method, that implements listing a queryset.</p>
|
||
<p>If the queryset is populated, this returns a <code>200 OK</code> response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated.</p>
|
||
<p>If the queryset is empty this returns a <code>200 OK</code> response, unless the <code>.allow_empty</code> attribute on the view is set to <code>False</code>, in which case it will return a <code>404 Not Found</code>.</p>
|
||
<h2 id="createmodelmixin">CreateModelMixin</h2>
|
||
<p>Provides a <code>.create(request, *args, **kwargs)</code> method, that implements creating and saving a new model instance.</p>
|
||
<p>If an object is created this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response. If the representation contains a key named <code>url</code>, then the <code>Location</code> header of the response will be populated with that value.</p>
|
||
<p>If the request data provided for creating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
|
||
<h2 id="retrievemodelmixin">RetrieveModelMixin</h2>
|
||
<p>Provides a <code>.retrieve(request, *args, **kwargs)</code> method, that implements returning an existing model instance in a response.</p>
|
||
<p>If an object can be retrieved this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response. Otherwise it will return a <code>404 Not Found</code>.</p>
|
||
<h2 id="updatemodelmixin">UpdateModelMixin</h2>
|
||
<p>Provides a <code>.update(request, *args, **kwargs)</code> method, that implements updating and saving an existing model instance.</p>
|
||
<p>Also provides a <code>.partial_update(request, *args, **kwargs)</code> method, which is similar to the <code>update</code> method, except that all fields for the update will be optional. This allows support for HTTP <code>PATCH</code> requests.</p>
|
||
<p>If an object is updated this returns a <code>200 OK</code> response, with a serialized representation of the object as the body of the response.</p>
|
||
<p>If an object is created, for example when making a <code>DELETE</code> request followed by a <code>PUT</code> request to the same URL, this returns a <code>201 Created</code> response, with a serialized representation of the object as the body of the response.</p>
|
||
<p>If the request data provided for updating the object was invalid, a <code>400 Bad Request</code> response will be returned, with the error details as the body of the response.</p>
|
||
<h2 id="destroymodelmixin">DestroyModelMixin</h2>
|
||
<p>Provides a <code>.destroy(request, *args, **kwargs)</code> method, that implements deletion of an existing model instance.</p>
|
||
<p>If an object is deleted this returns a <code>204 No Content</code> response, otherwise it will return a <code>404 Not Found</code>.</p>
|
||
<hr />
|
||
<h1 id="concrete-view-classes">Concrete View Classes</h1>
|
||
<p>The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior.</p>
|
||
<h2 id="createapiview">CreateAPIView</h2>
|
||
<p>Used for <strong>create-only</strong> endpoints.</p>
|
||
<p>Provides a <code>post</code> method handler.</p>
|
||
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#createmodelmixin">CreateModelMixin</a></p>
|
||
<h2 id="listapiview">ListAPIView</h2>
|
||
<p>Used for <strong>read-only</strong> endpoints to represent a <strong>collection of model instances</strong>.</p>
|
||
<p>Provides a <code>get</code> method handler.</p>
|
||
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#listmodelmixin">ListModelMixin</a></p>
|
||
<h2 id="retrieveapiview">RetrieveAPIView</h2>
|
||
<p>Used for <strong>read-only</strong> endpoints to represent a <strong>single model instance</strong>.</p>
|
||
<p>Provides a <code>get</code> method handler.</p>
|
||
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a></p>
|
||
<h2 id="destroyapiview">DestroyAPIView</h2>
|
||
<p>Used for <strong>delete-only</strong> endpoints for a <strong>single model instance</strong>.</p>
|
||
<p>Provides a <code>delete</code> method handler.</p>
|
||
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
|
||
<h2 id="updateapiview">UpdateAPIView</h2>
|
||
<p>Used for <strong>update-only</strong> endpoints for a <strong>single model instance</strong>.</p>
|
||
<p>Provides <code>put</code> and <code>patch</code> method handlers.</p>
|
||
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#updatemodelmixin">UpdateModelMixin</a></p>
|
||
<h2 id="listcreateapiview">ListCreateAPIView</h2>
|
||
<p>Used for <strong>read-write</strong> endpoints to represent a <strong>collection of model instances</strong>.</p>
|
||
<p>Provides <code>get</code> and <code>post</code> method handlers.</p>
|
||
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#listmodelmixin">ListModelMixin</a>, <a href="#createmodelmixin">CreateModelMixin</a></p>
|
||
<h2 id="retrieveupdateapiview">RetrieveUpdateAPIView</h2>
|
||
<p>Used for <strong>read or update</strong> endpoints to represent a <strong>single model instance</strong>.</p>
|
||
<p>Provides <code>get</code>, <code>put</code> and <code>patch</code> method handlers.</p>
|
||
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#updatemodelmixin">UpdateModelMixin</a></p>
|
||
<h2 id="retrievedestroyapiview">RetrieveDestroyAPIView</h2>
|
||
<p>Used for <strong>read or delete</strong> endpoints to represent a <strong>single model instance</strong>.</p>
|
||
<p>Provides <code>get</code> and <code>delete</code> method handlers.</p>
|
||
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
|
||
<h2 id="retrieveupdatedestroyapiview">RetrieveUpdateDestroyAPIView</h2>
|
||
<p>Used for <strong>read-write-delete</strong> endpoints to represent a <strong>single model instance</strong>.</p>
|
||
<p>Provides <code>get</code>, <code>put</code>, <code>patch</code> and <code>delete</code> method handlers.</p>
|
||
<p>Extends: <a href="#genericapiview">GenericAPIView</a>, <a href="#retrievemodelmixin">RetrieveModelMixin</a>, <a href="#updatemodelmixin">UpdateModelMixin</a>, <a href="#destroymodelmixin">DestroyModelMixin</a></p>
|
||
<hr />
|
||
<h1 id="customizing-the-generic-views">Customizing the generic views</h1>
|
||
<p>Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed.</p>
|
||
<h2 id="creating-custom-mixins">Creating custom mixins</h2>
|
||
<p>For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following:</p>
|
||
<pre class="prettyprint lang-py"><code>class MultipleFieldLookupMixin(object):
|
||
"""
|
||
Apply this mixin to any view or viewset to get multiple field filtering
|
||
based on a `lookup_fields` attribute, instead of the default single field filtering.
|
||
"""
|
||
def get_object(self):
|
||
queryset = self.get_queryset() # Get the base queryset
|
||
queryset = self.filter_queryset(queryset) # Apply any filter backends
|
||
filter = {}
|
||
for field in self.lookup_fields:
|
||
filter[field] = self.kwargs[field]
|
||
return get_object_or_404(queryset, **filter) # Lookup the object
|
||
</code></pre>
|
||
<p>You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior.</p>
|
||
<pre class="prettyprint lang-py"><code>class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
|
||
queryset = User.objects.all()
|
||
serializer_class = UserSerializer
|
||
lookup_fields = ('account', 'username')
|
||
</code></pre>
|
||
<p>Using custom mixins is a good option if you have custom behavior that needs to be used</p>
|
||
<h2 id="creating-custom-base-classes">Creating custom base classes</h2>
|
||
<p>If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:</p>
|
||
<pre class="prettyprint lang-py"><code>class BaseRetrieveView(MultipleFieldLookupMixin,
|
||
generics.RetrieveAPIView):
|
||
pass
|
||
|
||
class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
|
||
generics.RetrieveUpdateDestroyAPIView):
|
||
pass
|
||
</code></pre>
|
||
<p>Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project.</p>
|
||
<h1 id="third-party-packages">Third party packages</h1>
|
||
<p>The following third party packages provide additional generic view implementations.</p>
|
||
<h2 id="django-rest-framework-bulk">Django REST Framework bulk</h2>
|
||
<p>The <a href="https://github.com/miki725/django-rest-framework-bulk">django-rest-framework-bulk package</a> implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.</p>
|
||
</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://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
|
||
<script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script>
|
||
<script src="http://www.django-rest-framework.org/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();
|
||
});
|
||
|
||
// 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>
|