← Back to Journal

Filtering and ordering with Restless

Posted on 29 December 2014

Let’s continue with my previous blog post on Restless introduction with Django. Today I’ll show you two quick and simple Mixins for Restless. One for filtering and another for ordering.

I won’t show you how to create Django app, models, etc. This is not the subject.

Just to be clear, I have this models.py for our Pizza shop.

And my resources.py:

Filtering

We are building a very simple and not complete APIFilterMixin class.

As you can see allowed_fields_filter allow us to put filters (with lookup) that we want to authorize on our Resource.

This mixin only expose a single filter method which take one argument, a QuerySet instance.

At line 6 we just iterate over all request arguments, check if this argument is in allowed_fields_filter, update filters dictionary and at (line 9), we unpack filters in a filter method.

And this is updated revision of our previous resources.py with new mixin:

We can now give all filters we have allowed in allowed_fields_filter, including relation lookups.

Ordering

Ordering is even more simple than filtering. Look how restless allow us to cleanly create our minimal API.

This mixin support custom ordering field name with ordering_field. We can allow fields we want with allowed_fields_ordering. Another simple but cool feature is reverse ordering support (line 10).

Just add APIOrderingMixin to your PizzaResource and here we go.

Happy programming everybody!