<p>The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects.</p>
<p>The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.</p>
<p>The simplest way to filter the queryset of any view that subclasses <code>GenericAPIView</code> is to override the <code>.get_queryset()</code> method.</p>
<p>Overriding this method allows you to customize the queryset returned by the view in a number of different ways.</p>
<h2id="filtering-against-the-current-user">Filtering against the current user</h2>
<p>You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned.</p>
<p>You can do so by filtering based on the value of <code>request.user</code>.</p>
<h2id="filtering-against-query-parameters">Filtering against query parameters</h2>
<p>A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url.</p>
<p>We can override <code>.get_queryset()</code> to deal with URLs such as <code>http://example.com/api/purchases?username=denvercoder9</code>, and filter the queryset only if the <code>username</code> parameter is included in the URL:</p>
<p>As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters.</p>
<p>You can also set the filter backends on a per-view, or per-viewset basis,
using the <code>GenericAPIView</code> class based views.</p>
<preclass="prettyprint lang-py"><code>from django.contrib.auth.models import User
from myapp.serializers import UserSerializer
from rest_framework import filters
from rest_framework import generics
class UserListView(generics.ListAPIView):
queryset = User.objects.all()
serializer = UserSerializer
filter_backends = (filters.DjangoFilterBackend,)
</code></pre>
<h2id="filtering-and-object-lookups">Filtering and object lookups</h2>
<p>Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object.</p>
<p>For instance, given the previous example, and a product with an id of <code>4675</code>, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance:</p>
<h2id="overriding-the-initial-queryset">Overriding the initial queryset</h2>
<p>Note that you can use both an overridden <code>.get_queryset()</code> and generic filtering together, and everything will work as expected. For example, if <code>Product</code> had a many-to-many relationship with <code>User</code>, named <code>purchase</code>, you might want to write a view like this:</p>
<p>The <code>DjangoFilterBackend</code> class supports highly customizable field filtering, using the <ahref="https://github.com/alex/django-filter">django-filter package</a>. </p>
<p>To use REST framework's <code>DjangoFilterBackend</code>, first install <code>django-filter</code>.</p>
<p>If all you need is simple equality-based filtering, you can set a <code>filter_fields</code> attribute on the view, or viewset, listing the set of fields you wish to filter against.</p>
<p>For more details on using filter sets see the <ahref="https://django-filter.readthedocs.org/en/latest/index.html">django-filter documentation</a>.</p>
<hr/>
<p><strong>Hints & Tips</strong></p>
<ul>
<li>By default filtering is not enabled. If you want to use <code>DjangoFilterBackend</code> remember to make sure it is installed by using the <code>'DEFAULT_FILTER_BACKENDS'</code> setting.</li>
<li>When using boolean fields, you should use the values <code>True</code> and <code>False</code> in the URL query parameters, rather than <code>0</code>, <code>1</code>, <code>true</code> or <code>false</code>. (The allowed boolean values are currently hardwired in Django's <ahref="https://github.com/django/django/blob/master/django/forms/widgets.py">NullBooleanSelect implementation</a>.) </li>
<li><code>django-filter</code> supports filtering across relationships, using Django's double-underscore syntax.</li>
<li>For Django 1.3 support, make sure to install <code>django-filter</code> version 0.5.4, as later versions drop support for 1.3.</li>
</ul>
<hr/>
<h2id="searchfilter">SearchFilter</h2>
<p>The <code>SearchFilter</code> class supports simple single query parameter based searching, and is based on the <ahref="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields">Django admin's search functionality</a>.</p>
<p>The <code>SearchFilter</code> class will only be applied if the view has a <code>search_fields</code> attribute set. The <code>search_fields</code> attribute should be a list of names of text type fields on the model, such as <code>CharField</code> or <code>TextField</code>.</p>
<p>By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched.</p>
<p>The search behavior may be restricted by prepending various characters to the <code>search_fields</code>.</p>
<ul>
<li>'^' Starts-with search.</li>
<li>'=' Exact matches.</li>
<li>'@' Full-text search. (Currently only supported Django's MySQL backend.)</li>
<p>For more details, see the <ahref="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields">Django documentation</a>.</p>
<p>The <code>OrderingFilter</code> class supports simple query parameter controlled ordering of results. By default, the query parameter is named <code>'ordering'</code>, but this may by overridden with the <code>ORDERING_PARAM</code> setting.</p>
<h3id="specifying-which-fields-may-be-ordered-against">Specifying which fields may be ordered against</h3>
<p>It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an <code>ordering_fields</code> attribute on the view, like so:</p>
<p>This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data.</p>
<p>If you <em>don't</em> specify an <code>ordering_fields</code> attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the <code>serializer_class</code> attribute.</p>
<p>If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on <em>any</em> model field or queryset aggregate, by using the special value <code>'__all__'</code>.</p>
<p>If an <code>ordering</code> attribute is set on the view, this will be used as the default ordering.</p>
<p>Typically you'd instead control this by setting <code>order_by</code> on the initial queryset, but using the <code>ordering</code> parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results.</p>
<p>The <code>DjangoObjectPermissionsFilter</code> is intended to be used together with the <ahref="http://pythonhosted.org/django-guardian/"><code>django-guardian</code></a> package, with custom <code>'view'</code> permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission.</p>
<p>This filter class must be used with views that provide either a <code>queryset</code> or a <code>model</code> attribute.</p>
<p>If you're using <code>DjangoObjectPermissionsFilter</code>, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass <code>DjangoObjectPermissions</code> and add <code>'view'</code> permissions to the <code>perms_map</code> attribute.</p>
<p>A complete example using both <code>DjangoObjectPermissionsFilter</code> and <code>DjangoObjectPermissions</code> might look something like this.</p>
<p>For more information on adding <code>'view'</code> permissions for models, see the <ahref="http://pythonhosted.org/django-guardian/userguide/assign.html">relevant section</a> of the <code>django-guardian</code> documentation, and <ahref="http://blog.nyaruka.com/adding-a-view-permission-to-django-models">this blogpost</a>.</p>
<p>You can also provide your own generic filtering backend, or write an installable app for other developers to use.</p>
<p>To do so override <code>BaseFilterBackend</code>, and override the <code>.filter_queryset(self, request, queryset, view)</code> method. The method should return a new, filtered queryset.</p>
<p>As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user.</p>
<h2id="example">Example</h2>
<p>For example, you might need to restrict users to only being able to see objects they created.</p>
<p>We could achieve the same behavior by overriding <code>get_queryset()</code> on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API.</p>
<p>The <ahref="https://github.com/philipn/django-rest-framework-chain">django-rest-framework-chain package</a> works together with the <code>DjangoFilterBackend</code> class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field.</p>