django-rest-framework/api-guide/routers/index.html
2019-07-17 14:11:16 +00:00

797 lines
37 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<title>Routers - Django REST framework</title>
<link href="../../img/favicon.ico" rel="icon" type="image/x-icon">
<link rel="canonical" href="https://www.django-rest-framework.org/api-guide/routers/" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Django, API, REST, Routers">
<meta name="author" content="Tom Christie">
<!-- Le styles -->
<link href="../../css/prettify.css" rel="stylesheet">
<link href="../../css/bootstrap.css" rel="stylesheet">
<link href="../../css/bootstrap-responsive.css" rel="stylesheet">
<link href="../../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>
#sidebarInclude img {
margin-bottom: 10px;
}
#sidebarInclude a.promo {
color: black;
}
@media (max-width: 767px) {
div.promo {
display: none;
}
}
</style>
</head>
<body onload="prettyPrint()" class="-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/encode/django-rest-framework/tree/master">GitHub</a>
<a class="repo-link btn btn-inverse btn-small " rel="next" href="../parsers/">
Next <i class="icon-arrow-right icon-white"></i>
</a>
<a class="repo-link btn btn-inverse btn-small " rel="prev" href="../viewsets/">
<i class="icon-arrow-left icon-white"></i> Previous
</a>
<a id="search_modal_show" class="repo-link btn btn-inverse btn-small" href="#mkdocs_search_modal" data-toggle="modal" data-target="#mkdocs_search_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="https://www.django-rest-framework.org/">Django REST framework</a>
<div class="nav-collapse collapse">
<!-- Main navigation -->
<ul class="nav navbar-nav">
<li >
<a href="../..">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="../../tutorial/quickstart/">Quickstart</a>
</li>
<li >
<a href="../../tutorial/1-serialization/">1 - Serialization</a>
</li>
<li >
<a href="../../tutorial/2-requests-and-responses/">2 - Requests and responses</a>
</li>
<li >
<a href="../../tutorial/3-class-based-views/">3 - Class based views</a>
</li>
<li >
<a href="../../tutorial/4-authentication-and-permissions/">4 - Authentication and permissions</a>
</li>
<li >
<a href="../../tutorial/5-relationships-and-hyperlinked-apis/">5 - Relationships and hyperlinked APIs</a>
</li>
<li >
<a href="../../tutorial/6-viewsets-and-routers/">6 - Viewsets and routers</a>
</li>
</ul>
</li>
<li class="dropdown active">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
<ul class="dropdown-menu">
<li >
<a href="../requests/">Requests</a>
</li>
<li >
<a href="../responses/">Responses</a>
</li>
<li >
<a href="../views/">Views</a>
</li>
<li >
<a href="../generic-views/">Generic views</a>
</li>
<li >
<a href="../viewsets/">Viewsets</a>
</li>
<li class="active" >
<a href="./">Routers</a>
</li>
<li >
<a href="../parsers/">Parsers</a>
</li>
<li >
<a href="../renderers/">Renderers</a>
</li>
<li >
<a href="../serializers/">Serializers</a>
</li>
<li >
<a href="../fields/">Serializer fields</a>
</li>
<li >
<a href="../relations/">Serializer relations</a>
</li>
<li >
<a href="../validators/">Validators</a>
</li>
<li >
<a href="../authentication/">Authentication</a>
</li>
<li >
<a href="../permissions/">Permissions</a>
</li>
<li >
<a href="../caching/">Caching</a>
</li>
<li >
<a href="../throttling/">Throttling</a>
</li>
<li >
<a href="../filtering/">Filtering</a>
</li>
<li >
<a href="../pagination/">Pagination</a>
</li>
<li >
<a href="../versioning/">Versioning</a>
</li>
<li >
<a href="../content-negotiation/">Content negotiation</a>
</li>
<li >
<a href="../metadata/">Metadata</a>
</li>
<li >
<a href="../schemas/">Schemas</a>
</li>
<li >
<a href="../format-suffixes/">Format suffixes</a>
</li>
<li >
<a href="../reverse/">Returning URLs</a>
</li>
<li >
<a href="../exceptions/">Exceptions</a>
</li>
<li >
<a href="../status-codes/">Status codes</a>
</li>
<li >
<a href="../testing/">Testing</a>
</li>
<li >
<a href="../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="../../topics/documenting-your-api/">Documenting your API</a>
</li>
<li >
<a href="../../topics/api-clients/">API Clients</a>
</li>
<li >
<a href="../../topics/internationalization/">Internationalization</a>
</li>
<li >
<a href="../../topics/ajax-csrf-cors/">AJAX, CSRF & CORS</a>
</li>
<li >
<a href="../../topics/html-and-forms/">HTML & Forms</a>
</li>
<li >
<a href="../../topics/browser-enhancements/">Browser Enhancements</a>
</li>
<li >
<a href="../../topics/browsable-api/">The Browsable API</a>
</li>
<li >
<a href="../../topics/rest-hypermedia-hateoas/">REST, Hypermedia & HATEOAS</a>
</li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Community <b class="caret"></b></a>
<ul class="dropdown-menu">
<li >
<a href="../../community/tutorials-and-resources/">Tutorials and Resources</a>
</li>
<li >
<a href="../../community/third-party-packages/">Third Party Packages</a>
</li>
<li >
<a href="../../community/contributing/">Contributing to REST framework</a>
</li>
<li >
<a href="../../community/project-management/">Project management</a>
</li>
<li >
<a href="../../community/release-notes/">Release Notes</a>
</li>
<li >
<a href="../../community/3.10-announcement/">3.10 Announcement</a>
</li>
<li >
<a href="../../community/3.9-announcement/">3.9 Announcement</a>
</li>
<li >
<a href="../../community/3.8-announcement/">3.8 Announcement</a>
</li>
<li >
<a href="../../community/3.7-announcement/">3.7 Announcement</a>
</li>
<li >
<a href="../../community/3.6-announcement/">3.6 Announcement</a>
</li>
<li >
<a href="../../community/3.5-announcement/">3.5 Announcement</a>
</li>
<li >
<a href="../../community/3.4-announcement/">3.4 Announcement</a>
</li>
<li >
<a href="../../community/3.3-announcement/">3.3 Announcement</a>
</li>
<li >
<a href="../../community/3.2-announcement/">3.2 Announcement</a>
</li>
<li >
<a href="../../community/3.1-announcement/">3.1 Announcement</a>
</li>
<li >
<a href="../../community/3.0-announcement/">3.0 Announcement</a>
</li>
<li >
<a href="../../community/kickstarter-announcement/">Kickstarter Announcement</a>
</li>
<li >
<a href="../../community/mozilla-grant/">Mozilla Grant</a>
</li>
<li >
<a href="../../community/funding/">Funding</a>
</li>
<li >
<a href="../../community/jobs/">Jobs</a>
</li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
</div>
</div>
</div>
<div class="body-content">
<div class="container-fluid">
<!-- Search Modal -->
<div id="mkdocs_search_modal" 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">&times;</button>
<h3 id="myModalLabel">Documentation search</h3>
</div>
<div class="modal-body">
<form role="form" autocomplete="off">
<div class="form-group">
<input type="text" name="q" class="form-control" placeholder="Search..." id="mkdocs-search-query">
</div>
</form>
<div id="mkdocs-search-results"></div>
</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">
<div id="table-of-contents">
<ul class="nav nav-list side-nav well sidebar-nav-fixed">
<li class="main">
<a href="#routers">Routers</a>
</li>
<li>
<a href="#usage">Usage</a>
</li>
<li class="main">
<a href="#api-guide">API Guide</a>
</li>
<li>
<a href="#simplerouter">SimpleRouter</a>
</li>
<li>
<a href="#defaultrouter">DefaultRouter</a>
</li>
<li class="main">
<a href="#custom-routers">Custom Routers</a>
</li>
<li>
<a href="#customizing-dynamic-routes">Customizing dynamic routes</a>
</li>
<li>
<a href="#example">Example</a>
</li>
<li>
<a href="#advanced-custom-routers">Advanced custom routers</a>
</li>
<li class="main">
<a href="#third-party-packages">Third Party Packages</a>
</li>
<li>
<a href="#drf-nested-routers">DRF Nested Routers</a>
</li>
<li>
<a href="#modelrouter-wqdbrest">ModelRouter (wq.db.rest)</a>
</li>
<li>
<a href="#drf-extensions">DRF-extensions</a>
</li>
<div class="promo">
<hr/>
<div id="sidebarInclude">
</div>
</ul>
</div>
</div>
<div id="main-content" class="span9">
<a class="github" href="https://github.com/encode/django-rest-framework/tree/master/rest_framework/routers.py">
<span class="label label-info">routers.py</span>
</a>
<h1 id="routers"><a class="toclink" href="#routers">Routers</a></h1>
<blockquote>
<p>Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code.</p>
<p>&mdash; <a href="https://guides.rubyonrails.org/routing.html">Ruby on Rails Documentation</a></p>
</blockquote>
<p>Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests.</p>
<p>REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs.</p>
<h2 id="usage"><a class="toclink" href="#usage">Usage</a></h2>
<p>Here's an example of a simple URL conf, that uses <code>SimpleRouter</code>.</p>
<pre><code>from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = router.urls
</code></pre>
<p>There are two mandatory arguments to the <code>register()</code> method:</p>
<ul>
<li><code>prefix</code> - The URL prefix to use for this set of routes.</li>
<li><code>viewset</code> - The viewset class.</li>
</ul>
<p>Optionally, you may also specify an additional argument:</p>
<ul>
<li><code>basename</code> - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the <code>queryset</code> attribute of the viewset, if it has one. Note that if the viewset does not include a <code>queryset</code> attribute then you must set <code>basename</code> when registering the viewset.</li>
</ul>
<p>The example above would generate the following URL patterns:</p>
<ul>
<li>URL pattern: <code>^users/$</code> Name: <code>'user-list'</code></li>
<li>URL pattern: <code>^users/{pk}/$</code> Name: <code>'user-detail'</code></li>
<li>URL pattern: <code>^accounts/$</code> Name: <code>'account-list'</code></li>
<li>URL pattern: <code>^accounts/{pk}/$</code> Name: <code>'account-detail'</code></li>
</ul>
<hr />
<p><strong>Note</strong>: The <code>basename</code> argument is used to specify the initial part of the view name pattern. In the example above, that's the <code>user</code> or <code>account</code> part.</p>
<p>Typically you won't <em>need</em> to specify the <code>basename</code> argument, but if you have a viewset where you've defined a custom <code>get_queryset</code> method, then the viewset may not have a <code>.queryset</code> attribute set. If you try to register that viewset you'll see an error like this:</p>
<pre><code>'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute.
</code></pre>
<p>This means you'll need to explicitly set the <code>basename</code> argument when registering the viewset, as it could not be automatically determined from the model name.</p>
<hr />
<h3 id="using-include-with-routers"><a class="toclink" href="#using-include-with-routers">Using <code>include</code> with routers</a></h3>
<p>The <code>.urls</code> attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs.</p>
<p>For example, you can append <code>router.urls</code> to a list of existing views...</p>
<pre><code>router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
router.register(r'accounts', AccountViewSet)
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
]
urlpatterns += router.urls
</code></pre>
<p>Alternatively you can use Django's <code>include</code> function, like so...</p>
<pre><code>urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^', include(router.urls)),
]
</code></pre>
<p>You may use <code>include</code> with an application namespace:</p>
<pre><code>urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include((router.urls, 'app_name'))),
]
</code></pre>
<p>Or both an application and instance namespace:</p>
<pre><code>urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include((router.urls, 'app_name'), namespace='instance_name')),
]
</code></pre>
<p>See Django's <a href="https://docs.djangoproject.com/en/1.11/topics/http/urls/#url-namespaces">URL namespaces docs</a> and the <a href="https://docs.djangoproject.com/en/2.0/ref/urls/#include"><code>include</code> API reference</a> for more details.</p>
<hr />
<p><strong>Note</strong>: If using namespacing with hyperlinked serializers you'll also need to ensure that any <code>view_name</code> parameters
on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as
<code>view_name='app_name:user-detail'</code> for serializer fields hyperlinked to the user detail view.</p>
<p>The automatic <code>view_name</code> generation uses a pattern like <code>%(model_name)-detail</code>. Unless your models names actually clash
you may be better off <strong>not</strong> namespacing your Django REST Framework views when using hyperlinked serializers.</p>
<hr />
<h3 id="routing-for-extra-actions"><a class="toclink" href="#routing-for-extra-actions">Routing for extra actions</a></h3>
<p>A viewset may <a href="../viewsets/#marking-extra-actions-for-routing">mark extra actions for routing</a> by decorating a method with the <code>@action</code> decorator. These extra actions will be included in the generated routes. For example, given the <code>set_password</code> method on the <code>UserViewSet</code> class:</p>
<pre><code>from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import action
class UserViewSet(ModelViewSet):
...
@action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
</code></pre>
<p>The following route would be generated:</p>
<ul>
<li>URL pattern: <code>^users/{pk}/set_password/$</code></li>
<li>URL name: <code>'user-set-password'</code></li>
</ul>
<p>By default, the URL pattern is based on the method name, and the URL name is the combination of the <code>ViewSet.basename</code> and the hyphenated method name.
If you don't want to use the defaults for either of these values, you can instead provide the <code>url_path</code> and <code>url_name</code> arguments to the <code>@action</code> decorator.</p>
<p>For example, if you want to change the URL for our custom action to <code>^users/{pk}/change-password/$</code>, you could write:</p>
<pre><code>from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import action
class UserViewSet(ModelViewSet):
...
@action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf],
url_path='change-password', url_name='change_password')
def set_password(self, request, pk=None):
...
</code></pre>
<p>The above example would now generate the following URL pattern:</p>
<ul>
<li>URL path: <code>^users/{pk}/change-password/$</code></li>
<li>URL name: <code>'user-change_password'</code></li>
</ul>
<h1 id="api-guide"><a class="toclink" href="#api-guide">API Guide</a></h1>
<h2 id="simplerouter"><a class="toclink" href="#simplerouter">SimpleRouter</a></h2>
<p>This router includes routes for the standard set of <code>list</code>, <code>create</code>, <code>retrieve</code>, <code>update</code>, <code>partial_update</code> and <code>destroy</code> actions. The viewset can also mark additional methods to be routed, using the <code>@action</code> decorator.</p>
<table border=1>
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
<tr><td rowspan=2>{prefix}/</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
<tr><td>POST</td><td>create</td></tr>
<tr><td>{prefix}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
<tr><td rowspan=4>{prefix}/{lookup}/</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
<tr><td>PUT</td><td>update</td></tr>
<tr><td>PATCH</td><td>partial_update</td></tr>
<tr><td>DELETE</td><td>destroy</td></tr>
<tr><td>{prefix}/{lookup}/{url_path}/</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
</table>
<p>By default the URLs created by <code>SimpleRouter</code> are appended with a trailing slash.
This behavior can be modified by setting the <code>trailing_slash</code> argument to <code>False</code> when instantiating the router. For example:</p>
<pre><code>router = SimpleRouter(trailing_slash=False)
</code></pre>
<p>Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style.</p>
<p>The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the <code>lookup_value_regex</code> attribute on the viewset. For example, you can limit the lookup to valid UUIDs:</p>
<pre><code>class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet):
lookup_field = 'my_model_id'
lookup_value_regex = '[0-9a-f]{32}'
</code></pre>
<h2 id="defaultrouter"><a class="toclink" href="#defaultrouter">DefaultRouter</a></h2>
<p>This router is similar to <code>SimpleRouter</code> as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional <code>.json</code> style format suffixes.</p>
<table border=1>
<tr><th>URL Style</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
<tr><td>[.format]</td><td>GET</td><td>automatically generated root view</td><td>api-root</td></tr></tr>
<tr><td rowspan=2>{prefix}/[.format]</td><td>GET</td><td>list</td><td rowspan=2>{basename}-list</td></tr></tr>
<tr><td>POST</td><td>create</td></tr>
<tr><td>{prefix}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=False)` decorated method</td><td>{basename}-{url_name}</td></tr>
<tr><td rowspan=4>{prefix}/{lookup}/[.format]</td><td>GET</td><td>retrieve</td><td rowspan=4>{basename}-detail</td></tr></tr>
<tr><td>PUT</td><td>update</td></tr>
<tr><td>PATCH</td><td>partial_update</td></tr>
<tr><td>DELETE</td><td>destroy</td></tr>
<tr><td>{prefix}/{lookup}/{url_path}/[.format]</td><td>GET, or as specified by `methods` argument</td><td>`@action(detail=True)` decorated method</td><td>{basename}-{url_name}</td></tr>
</table>
<p>As with <code>SimpleRouter</code> the trailing slashes on the URL routes can be removed by setting the <code>trailing_slash</code> argument to <code>False</code> when instantiating the router.</p>
<pre><code>router = DefaultRouter(trailing_slash=False)
</code></pre>
<h1 id="custom-routers"><a class="toclink" href="#custom-routers">Custom Routers</a></h1>
<p>Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view.</p>
<p>The simplest way to implement a custom router is to subclass one of the existing router classes. The <code>.routes</code> attribute is used to template the URL patterns that will be mapped to each viewset. The <code>.routes</code> attribute is a list of <code>Route</code> named tuples.</p>
<p>The arguments to the <code>Route</code> named tuple are:</p>
<p><strong>url</strong>: A string representing the URL to be routed. May include the following format strings:</p>
<ul>
<li><code>{prefix}</code> - The URL prefix to use for this set of routes.</li>
<li><code>{lookup}</code> - The lookup field used to match against a single instance.</li>
<li><code>{trailing_slash}</code> - Either a '/' or an empty string, depending on the <code>trailing_slash</code> argument.</li>
</ul>
<p><strong>mapping</strong>: A mapping of HTTP method names to the view methods</p>
<p><strong>name</strong>: The name of the URL as used in <code>reverse</code> calls. May include the following format string:</p>
<ul>
<li><code>{basename}</code> - The base to use for the URL names that are created.</li>
</ul>
<p><strong>initkwargs</strong>: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the <code>detail</code>, <code>basename</code>, and <code>suffix</code> arguments are reserved for viewset introspection and are also used by the browsable API to generate the view name and breadcrumb links.</p>
<h2 id="customizing-dynamic-routes"><a class="toclink" href="#customizing-dynamic-routes">Customizing dynamic routes</a></h2>
<p>You can also customize how the <code>@action</code> decorator is routed. Include the <code>DynamicRoute</code> named tuple in the <code>.routes</code> list, setting the <code>detail</code> argument as appropriate for the list-based and detail-based routes. In addition to <code>detail</code>, the arguments to <code>DynamicRoute</code> are:</p>
<p><strong>url</strong>: A string representing the URL to be routed. May include the same format strings as <code>Route</code>, and additionally accepts the <code>{url_path}</code> format string.</p>
<p><strong>name</strong>: The name of the URL as used in <code>reverse</code> calls. May include the following format strings:</p>
<ul>
<li><code>{basename}</code> - The base to use for the URL names that are created.</li>
<li><code>{url_name}</code> - The <code>url_name</code> provided to the <code>@action</code>.</li>
</ul>
<p><strong>initkwargs</strong>: A dictionary of any additional arguments that should be passed when instantiating the view.</p>
<h2 id="example"><a class="toclink" href="#example">Example</a></h2>
<p>The following example will only route to the <code>list</code> and <code>retrieve</code> actions, and does not use the trailing slash convention.</p>
<pre><code>from rest_framework.routers import Route, DynamicRoute, SimpleRouter
class CustomReadOnlyRouter(SimpleRouter):
"""
A router for read-only APIs, which doesn't use trailing slashes.
"""
routes = [
Route(
url=r'^{prefix}$',
mapping={'get': 'list'},
name='{basename}-list',
detail=False,
initkwargs={'suffix': 'List'}
),
Route(
url=r'^{prefix}/{lookup}$',
mapping={'get': 'retrieve'},
name='{basename}-detail',
detail=True,
initkwargs={'suffix': 'Detail'}
),
DynamicRoute(
url=r'^{prefix}/{lookup}/{url_path}$',
name='{basename}-{url_name}',
detail=True,
initkwargs={}
)
]
</code></pre>
<p>Let's take a look at the routes our <code>CustomReadOnlyRouter</code> would generate for a simple viewset.</p>
<p><code>views.py</code>:</p>
<pre><code>class UserViewSet(viewsets.ReadOnlyModelViewSet):
"""
A viewset that provides the standard actions
"""
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_field = 'username'
@action(detail=True)
def group_names(self, request, pk=None):
"""
Returns a list of all the group names that the given
user belongs to.
"""
user = self.get_object()
groups = user.groups.all()
return Response([group.name for group in groups])
</code></pre>
<p><code>urls.py</code>:</p>
<pre><code>router = CustomReadOnlyRouter()
router.register('users', UserViewSet)
urlpatterns = router.urls
</code></pre>
<p>The following mappings would be generated...</p>
<table border=1>
<tr><th>URL</th><th>HTTP Method</th><th>Action</th><th>URL Name</th></tr>
<tr><td>/users</td><td>GET</td><td>list</td><td>user-list</td></tr>
<tr><td>/users/{username}</td><td>GET</td><td>retrieve</td><td>user-detail</td></tr>
<tr><td>/users/{username}/group_names</td><td>GET</td><td>group_names</td><td>user-group-names</td></tr>
</table>
<p>For another example of setting the <code>.routes</code> attribute, see the source code for the <code>SimpleRouter</code> class.</p>
<h2 id="advanced-custom-routers"><a class="toclink" href="#advanced-custom-routers">Advanced custom routers</a></h2>
<p>If you want to provide totally custom behavior, you can override <code>BaseRouter</code> and override the <code>get_urls(self)</code> method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the <code>self.registry</code> attribute.</p>
<p>You may also want to override the <code>get_default_basename(self, viewset)</code> method, or else always explicitly set the <code>basename</code> argument when registering your viewsets with the router.</p>
<h1 id="third-party-packages"><a class="toclink" href="#third-party-packages">Third Party Packages</a></h1>
<p>The following third party packages are also available.</p>
<h2 id="drf-nested-routers"><a class="toclink" href="#drf-nested-routers">DRF Nested Routers</a></h2>
<p>The <a href="https://github.com/alanjds/drf-nested-routers">drf-nested-routers package</a> provides routers and relationship fields for working with nested resources.</p>
<h2 id="modelrouter-wqdbrest"><a class="toclink" href="#modelrouter-wqdbrest">ModelRouter (wq.db.rest)</a></h2>
<p>The <a href="https://wq.io/wq.db">wq.db package</a> provides an advanced <a href="https://wq.io/docs/router">ModelRouter</a> class (and singleton instance) that extends <code>DefaultRouter</code> with a <code>register_model()</code> API. Much like Django's <code>admin.site.register</code>, the only required argument to <code>rest.router.register_model</code> is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration.</p>
<pre><code>from wq.db import rest
from myapp.models import MyModel
rest.router.register_model(MyModel)
</code></pre>
<h2 id="drf-extensions"><a class="toclink" href="#drf-extensions">DRF-extensions</a></h2>
<p>The <a href="https://chibisov.github.io/drf-extensions/docs/"><code>DRF-extensions</code> package</a> provides <a href="https://chibisov.github.io/drf-extensions/docs/#routers">routers</a> for creating <a href="https://chibisov.github.io/drf-extensions/docs/#nested-routes">nested viewsets</a>, <a href="https://chibisov.github.io/drf-extensions/docs/#collection-level-controllers">collection level controllers</a> with <a href="https://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name">customizable endpoint names</a>.</p>
</div> <!--/span-->
</div> <!--/row-->
</div> <!--/.fluid-container-->
</div> <!--/.body content-->
<div id="push"></div>
</div> <!--/.wrapper -->
<footer class="span12">
<p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.
</p>
</footer>
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script async src="https://fund.django-rest-framework.org/sidebar_include.js"></script>
<script src="../../js/jquery-1.8.1-min.js"></script>
<script src="../../js/prettify-1.0.js"></script>
<script src="../../js/bootstrap-2.1.1-min.js"></script>
<script src="../../js/theme.js"></script>
<script>var base_url = '../..';</script>
<script src="../../search/main.js" defer></script>
<script>
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/dropdown to no higher than browser window
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
$(function() {
$(window).resize(function() {
$('.side-nav, .dropdown-menu').css('max-height', window.innerHeight - 130);
});
});
</script>
</body>
</html>