Django serializers vs rest_framework serializers

2024/9/20 0:13:20

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/

Answer

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 HttpResponseclass 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 = Employeefields = ('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 HttpResponseclass 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 viewsetsclass 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.

https://en.xdnf.cn/q/72539.html

Related Q&A

Pandas replace non-zero values

I know I can replace all nan values with df.fillna(0) and replace a single value with df.replace(-,1), but how can I replace all non-zero values with a single value?

Pandas percentage change using group by

Suppose I have the following DataFrame: df = pd.DataFrame({city: [a, a, a, b, b, c, d, d, d], year: [2013, 2014, 2016, 2015, 2016, 2013, 2016, 2017, 2018],value: [10, 12, 16, 20, 21, 11, 15, 13, 16]})A…

Django cannot find my static files

I am relatively new to web dev. and I am trying to build my first web application. I have my static folder in project_root/static but for some reason, I keep getting 404s when I run the server:Not Foun…

How can I find intersection of two large file efficiently using python?

I have two large files. Their contents looks like this:134430513125296589151963957125296589The file contains an unsorted list of ids. Some ids may appear more than one time in a single file. Now I want…

Failed to load the native TensorFlow runtime - TensorFlow 2.1

I have a desktop computer and a notebook, when I tried to install tensorflow on a notebook just by using pip install tensorflow it worked ok, then I tried the same on my desktop computer and when I tri…

(Python) Issues with directories that have special characters

OS: Windows server 03 Python ver: 2.7For the code below, its runs fine when I substitute "[email protected]" with "fuchida". If I use the email format for directory name I get the f…

LibCST: Converting arbitrary nodes to code

Is it possible to dump an arbitrary LibCST node into Python code? My use case is that I want to extract the code for functions that match a specific naming scheme. I can extract the FunctionDef nodes …

calculating the number of k-combinations with and without SciPy

Im puzzled by the fact that the function comb of SciPy appears to be slower than a naive Python implementation. This is the measured time for two equivalent programs solving the Problem 53 of Project E…

How to subclass requests in python through inheritance

I would like to specialize / subclass the requests package to add some method with custom functionality.I tried to do this:# concrete_requests.py import requestsclass concreteRequests(requests):def __i…

ipython debugger: full traceback on interactive pdb?

I recently switched from ipython0.10 to ipython0.11. In ipython0.11, I only see a small snippet of the full traceback when the python debugger engages (i.e. using %pdb), whereas in ipython0.10 Id see …