Currently I have started learning django rest framework and I came accross below kind of code for getting serializer object.
1)serializer = self.get_serializer(queryset, many=True)
2)serializer = MyDataTypeSerializer(queryset, many=True)
By using above two method I am able to get almost same kind of output so I have tried to find difference between those but not able to find any.
I have used above method likewise in my viewset.
class MyDataTypeViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = MyDataTypeSerializer
permission_classes = [IsAuthenticated]
queryset = MyDataType.objects.all()
def get_queryset(self):
return self.queryset.filter(user_id=self.request.user.id).order_by('-created_at')
def list(self, request, *args, **kwargs):
queryset = self.get_queryset()
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
serializer = self.get_paginated_response(serializer.data)
return return_success(serializer.data)
serializer = self.get_serializer(queryset, many=True)
#serializer = MyDataTypeSerializer(queryset, many=True)
return return_success(serializer.data)
Please if anyone knows let me know difference between these two methods and how to decide which method to use in which condition.
Thanks,
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators. It includes simple default implementations of .
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc. Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.
If you work with Django rest API. So serializer is a good option to convert data into JSON format. If you don't want to use a serializer you can use Django form rather than serializer.
get_serializer()
also takes care of passing in the viewset's serializer context, and calls get_serializer_class()
to figure out which serializer class to use.
Unless that function has been customized from the viewset default as linked by Andrew in the comments, and serializer_class = MyDataTypeSerializer
has been set,
serializer = self.get_serializer(queryset, many=True)
is exactly equivalent to
serializer = MyDataTypeSerializer(
queryset,
many=True,
context=self.get_serializer_context(),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With