From the course: Building RESTful Web APIs with Django
Filter back ends with URL query parameters
From the course: Building RESTful Web APIs with Django
Filter back ends with URL query parameters
- [Instructor] Now that we have a REST API that lists products, we can add product filtering using URL query parameters. In particular, we are going to be filtering products by whether they match a specific product ID, or whether they are on sale or not. We import Django-filters, rest framework, filter backend, and then we add it to the product list. We set filter backends to the DjangoFilterBackend, and we set the filter fields to just the ID. The filter fields variable is the setting for Django-filters that will enable filtering by specific fields in the data. Right now, we just have it enabled for the ID field. Let's see how this looks like in the browser with the server running. We refresh, and we can now see a new button called filters. We open it up, and now we can filter by the ID. So let's try that out. You can see only one product is returned, and we can also do this from the URL itself. And again, you can see the products are filtered by the specific ID. Let's return to the code and do something a little bit more complex. Let's filter the product by whether they are on sale or not. For this, we have to override the get queryset method. We're going to extract the URL parameter from the request. If the filter is set to none, we won't be doing any filtering. But if the on sale filter is set, we're going to be filtering all the products by whether they are on sale or not. We import django.utils.timezone so that we can get the current time, and then we apply the sales dates filters. Now let's try this in the browser. On sale equals true, and you can see only two products are returned, which have is on sale set to true. If we set this to false, you can see all products are returned. And that's how we can filter a product queryset using URL query parameters.
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
Creating a Django Rest framework serializer to serialize a model4m 11s
-
(Locked)
Creating a ListAPIView subclass1m 43s
-
(Locked)
Connecting an APIView to a route1m 53s
-
Filter back ends with URL query parameters3m 23s
-
(Locked)
Enabling full-text search filter back end2m 19s
-
(Locked)
Enabling pagination of querysets in API responses2m 58s
-
-
-
-
-