I am using viewsets in Django rest framework. I have seen many examples that serializer is being used every where. What if I don't want to use serializer, or what if I don't have a Model to use serializer? And I just want to return simple response data?
Below is just an example of how I am using it.
from rest_framework.response import Response
from rest_framework import status, viewsets
class UserViewSet(viewsets.ViewSet):
def create(self, request):
data = {'name': 'Shiv', 'email':'example@gmail.com'}
return Response(data, status=status.HTTP_201_CREATED)
As you can see, I don't have a serializer and the code works perfectly fine. So is this a good practice?
(I posted the same question in Code Review portal but not getting enough response).
As you can see, I don't have a serializer and the code works perfectly fine. So is this a good practice?
Is it mandatory? No, but it is often convenient.
A ViewSet
is, as the name already suggests, a set of views. So typically it is not meant to implement only one functionality, but several functionalities. For example retrieve the list of records, retrieve details of a record, create a new record, update an existing record, and delete an existing record. We do not need a serializer for that, but it would require writing a lot of code. If you later add a field to your model, it would require updating most of these functions, which thus requires more effort.
A serializer is a tool to define often a bi-directional mapping between models and their serialized representation. It thus makes it more convenient to retrieve data from a model object as well as creating and updating such object. You thus specify how the mapping works, but you do not need to implement these three functions yourself, or at least most of the logic is abstracted away.
Using serializer thus is meant to reduce the amount of work, and make the software less error-prone.