Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django serializers vs rest_framework serializers

What is the difference between Django serializers vs rest_framework serializers? I making a webapp, where I want the API to be part of the primary app created by the project. Not creating a separate App for the API functionality. Which serializer do I need to use for Django views and models, and at the same time will work for the API?

from django.core import serializers

https://docs.djangoproject.com/en/3.0/topics/serialization/

from rest_framework import serializers

https://www.django-rest-framework.org/api-guide/serializers/

like image 723
Majoris Avatar asked Jan 25 '23 05:01

Majoris


2 Answers

tl;dr

If you want to create just a few very small API endpoints and don't want to use DRF, you're better off manually building the dictionaries. Django core serializers are not meant for external consumers.


You can use the same primary app in your project and make it work with DRF in parallel. Just add a serializers.py file with the definitions, add the DRF logic in the same views.py file and do the routing. You could use function based views.

Detailed explanation of differences

Let's say you have the following model

class Employee(models.Model):
  identification_number = models.CharField(max_length=12)
  first_name = models.CharField(max_length=50)
  last_name = models.CharField(max_length=50)

And you want to create an endpoint /employees/ that returns all such objects with JSON representation

{
  "first_name": "Jon",
  "last_name": "Skeet"
}

With Django serializers

from django.core import serializers
from django.http import HttpResponse

class EmployeeView(View):
    def get(self, request):
        employees = Employee.objects.all()
        serialized = serializers.serialize(
          'json',
          employees,
          fields=('first_name', 'last_name'),
        )
        return HttpResponse(serialized)

and the result you get would be a list of dictionaries of the form

{
      "fields" : {
         "first_name" : "Jon",
         "last_name" : "Skeet"
      },
      "model" : "employees.Employee",
      "pk" : 12
}

But this isn't what we're looking for. Django core serializers are meant to serialize models as representations of what's in the database. This is made explicit by the fact that the dumpdata command uses it.

python manage.py dumpdata employees.Employee | json_pp
[
  {
      "fields" : {
         "identification_number" : "20201293",
         "first_name" : "Jon",
         "last_name" : "Skeet"
      },
      "model" : "employees.Employee",
      "pk" : 12
  }
]

Now, of course you could do some things to your code to get the representation you want, but this module is not meant to be used for API views to be consumed by a external consumer.


With Django REST framework

Here we can create serializer classes that are independent of the Model. This is important since the external representation of the object is kept separate from the internal one.

class EmployeeSerializer(serializers.ModelSerializer):

  class Meta:
    model = Employee
    fields = (
      'first_name',
      'last_name',
    )

and, trying to use only the most basic serialization-deserialization features of DRF, we would get

from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse

class EmployeeView(View):
    def get(self, request):
        employees = Employee.objects.all()
        serialized = EmployeeSerializer(employees, many=True)
        json_representation = JSONRenderer().render(serialized.data)
        return HttpResponse(json_representation)

and result in the representation we were looking for.

Now, of course you usually don't use DRF as in the last example, but instead

from rest_framework import viewsets

class EmployeeViewSet(viewsets.ReadOnlyModelViewSet):
  queryset = Employee.objects.all()
  serializer_class = EmployeeSerializer

It takes care of all the boilerplate so it's really convenient and, in contrast with the Django core serializers, this is really meant for external consumers.

like image 179
Kevin Languasco Avatar answered Jan 31 '23 08:01

Kevin Languasco


It's a default vs advanced situation. The Django serialize has just one page of documentation, while Django Rest has a whole website for it. If your application uses a lot of APIs, then it makes sense to install a whole framework. But for smaller APIs you'd just use the default Django one. No need to use both at the same time. Also, use serializers in views.

like image 25
jTiKey Avatar answered Jan 31 '23 09:01

jTiKey