Django Rest Framework Serialization Tutorial Part 3

Requirements

In order to complete this tutorial you need to have completed Django Rest Framework Serialization Tutorial Part 2.

Objective

After completing this tutorial you will gain more familiarity with the django Rest Framework's views classes.

In this tutorial we will refactor our code to use class based views in order to re-use common functionality and to keep our code DRY (Don't Repeat Yourself). 

Steps

In order to use class based views we will need to import some additional packages.

In your views.py file add the following import:

from django.http import Http404
from rest_framework.views import APIView

Next we will remove the existing datarow_list and datarow_detail methods. 

Next define the DataRowList class by adding the following code:

class DataRowList(APIView):
"""
List all datarow, or create a new datarow.
"""
def get(self, request, format=None):
datarow = DataRow.objects.all()
serializer = DataRowSerializers(datarow, many=True)
return Response(serializer.data)

def post(self,request,format=None):
serializer = DataRowSerializers(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

You will notice that there is a lot of similarity using the class based view over the method based views in the previous tutorial. However, there is more separation between the two HTTP methods which is good programming practice.

Next we will update the method for the data entry instances by replacing the datarow_list method with a class inheriting the APIView class. 

class DataRowDetail(APIView):
'''
Retrieve, update or delete a DataRow object.
'''
def get_object(self,pk):
try:
datarow=DataRow.objects.get(pk=pk)
except DataRow.DoesNotExist:
raise Http404

def get(self, request, pk, format=None):
datarow = self.get_object(pk)
serializer = DataRowSerializers(datarow)
return Response(serializer.data)

def put(self, request, pk, format=None):
datarow = self.get_object(pk)
serializer = DataRowSerializers(datarow, data=request.data)

def delete(self, request, pk, format=None):
datarow = self.get_object(pk)
datarow.delete()
return Response(status=status.HTTP_204_NO_CONTENT)

Again this should look quite similar to the method based views covered in the previous tutorial except using the class based views each if-elif block has been encapsulated in its own respective method inside the class.

Next we will need to adjust the urls.py to make sure the correct class based views are called when the user goes to the respective urls.

 url(r'^datarows/$',views.DataRowList.as_view()),
url(r'^datarows/(?P<pk>[0-9]+)/$', views.DataRowDetail.as_view()),

We have now moved to using class based views. You can try querying the server using curl like in the previous tutorial. You should get the same data returned.

Conclusion

We now have class based views that will make our code a lot more simply and DRY. The implications of this is that we can now use mixins which enables us to more easily compose reusable bits of code. This will be covered in the next part of this tutorial: Django Rest Framework Tutorial Part 4 Mixins

Subscribe to our mailing list

* indicates required