HTTPS SSH

Django Rest Framework Filtering

Adds Django ORM like filtering Django Rest Framework List views.

Installation

  1. Install django-rest-framework-filtering to your environment. -- pip install hg+http://bitbucket.org/mjs7231/django-rest-framework-filtering

  2. Add the app "rest_framework_filtering" to your Django project's INSTALLED_APPS.

  3. In your RestFramework API Views, replace inherit from "ListFilterCreateAPIView" rather than the default "ListCreateAPIView".

Example

from rest_framework_filtering.views import ListFilterCreateAPIView
class MenuList(ListFilterCreateAPIView):
    model = models.Menu
    serializer_class = serializers.MenuSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,)

Usage

Filtering works exactly like Django's ORM filtering except key names should be the fields specified in the Serializer's (not the Django model fields they refer to).

If can test this is working directly from the Rest Framework's Browsable API if you are using it. Simple navigate to the view that you updated with filtering and append your filter as GET arguments on the address bar.

For example, If your ListView is located at: http://localhost:8000/api/v1/menu/, you can start adding GET arguments to the end to filter the result set returned.

http://localhost:8000/api/v1/menu/?name__icontains=PK
http://localhost:8000/api/v1/menu/?name__icontains=PK&order_by=-name

Supported Field Lookups

  • The following filters are supported: isnull, year, month, day, week_day, contains, icontains, startswith, istartswith, endswith, iendswith, search, regex, iregex
  • To exclude (rather than filter) simply add a "-" in front of the filter. For example: "-id=123".
  • Ordering is supported with the "order_by" key.

Unsupported Features

  • Currently RelatedFields and HyperlinkRelatedFields can not be navigated.
  • All Django's Field Lookups are supported except for: "range" and "in".