DRF ModelViewSet CRUD with Sorting, Search and Pagination

Manish Sharma
2 min readJul 7, 2023

--

DRF ModelViewSet CRUD with Sorting, Search and Pagination

This is part-2 of the DRF/Django Tutorial series.

All tutorials: Part-1 Part-2 Part-3 Part-4 Part-5 Part-6

DRF (Django Rest Framework) makes Web API Development easier for Django App. REST based Web APIs often manipulates data such by creating new entities or updating, deleting existing entities. Such operations are collectively known as CRUD [Create, Read, Update, Delete] operations .

There are more than one ways of implementing CRUD in DRF. Since DRf follows “batteries included” approach, it makes CRUD Development easier with features like searching, sorting, pagination etc.

What are Views?

Views in DRF are functions or classes that generates response, most often JSON response upon request from client.

What is a ViewSet ?

Viewset combines logic for CRUD in a single class. This is similar to RESTFUL Controllers in Spring or Laravel.

What is ModelViewSet ?

It is a special ViewSet that provides default implementation of CRUD operations. All that we have to do is to provide

queryset : to retreive data
serializer_class : for object serialization
pagination_class: In case we are implementing pagination

Let’s see it in action

ModelVieSet with Pagination and search

Line# 8 : We have provided default queryset

Line# 12–24 : queryset customization

First get default query set

queryset = super().get_queryset()

Check if we have “kw” param. If so apply filter

kw = self.request.query_params.get('kw')
if kw is not None:
queryset = queryset.filter(title__contains=kw)

Check if we have “query” param. If so apply ordering

order = self.request.query_params.get('order')
if order is not None:
fields = ['id', '-id','title','title']
if order in fields:
queryset = queryset.order_by(order)
else:
raise ValidationError({'errror': 'order field must be in ' + ', '.join(fields)})

We have used “CustomPagination” class for pagination:

pagination_class = CustomPagination

It is defined as:

Now lets understand how it works

ModelViewSet implementation of CRUD with sorting, search and pagination
ModelViewSet implementation of CRUD with sorting, search and pagination

If we execute

http://127.0.0.1:8000/api/v1/notices/?p=2&kw=Hello&order=-id

It will return second page containing Hello in title ordered by id in descending.

PUT vs PATCH

There are two ways of updating an existing record

PUT : requires you pass all mandatory fields (title and description). This is (complete) update

PATCH : You may pass necessary fields only (title or description or both). This is partial update.

URL mapping

First create api.py

Now update urls.py to use api.py as follows:

You may download source code at https://github.com/mansha99/drf-modelviewset-pagination-search

Happy Coding.

--

--