djangorest serializer returns empty object

  • Last Update :
  • Techknowledgy :

You should use many=True serializer's argument to serialize multiple objects. Also you can pass directly as Response argument:

@permission_classes((permissions.AllowAny, ))
def get_all_workers(request):
   data = Workers.objects.using('rh').all().order_by('emp_cod')
serializer = WorkersSerializer(data, many = True)
return Response(

Since your view return so many objects at once, I suggest you to add pagination:

from rest_framework.pagination
import PageNumberPagination

@permission_classes((permissions.AllowAny, ))
def get_all_workers(request):
   data = Workers.objects.using('rh').all().order_by('emp_cod')
paginator = PageNumberPagination()
paginator.page_size = 10
result_page = paginator.paginate_queryset(data, request)
serializer = WorkersSerializer(result_page, many = True)
return Response(

Suggestion : 2

I want the serializer to return an empty response when no User DoesNotExist in the User Model, however I get the following error. How can i achieve this?,You are trying to serialize a queryset, so you need to add many=True to the serialization.

class User_ListView(APIView):
   permission_classes = [DjangoCustomModelPermissions]
queryset = User.objects.none()

def get(self, request):
   param1 = request.query_params.get('param1', None)
param2 = request.query_params.get('param2', None)

db_data = User.objects.get(param1 = param1, param2 = param2)
serializer = User_Serializer(db_data)
return Response(
except Closing_Stock_List_Trans.DoesNotExist:
   db_data = User.objects.none()
serializer = User_Serializer(db_data)
return Response(
class User_Serializer(serializers.ModelSerializer):
   class Meta:
   model = User
fields = '__all__'
AttributeError: Got AttributeError when attempting to get a value
for field `param1`
on serializer `User_Serializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet`
Original exception text was: 'QuerySet'
object has no attribute 'param1'.
except Closing_Stock_List_Trans.DoesNotExist:
   db_data = User.objects.none()
serializer = User_Serializer(db_data, many = True)
return Response(

Suggestion : 3

At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into json.,We'll also need to create an initial migration for our snippet model, and sync the database for the first time.,The first part of the serializer class defines the fields that get serialized/deserialized. The create() and update() methods define how fully fledged instances are created or modified when calling,...then we restore those native datatypes into a fully populated object instance.

Before we do anything else we'll create a new virtual environment, using venv. This will make sure our package configuration is kept nicely isolated from any other projects we're working on.

python3 - m venv env
source env / bin / activate

Now that we're inside a virtual environment, we can install our package requirements.

pip install django
pip install djangorestframework
pip install pygments # We 'll be using this for the code highlighting

Okay, we're ready to get coding. To get started, let's create a new project to work with.

   django - admin startproject tutorial
cd tutorial

We'll need to add our new snippets app and the rest_framework app to INSTALLED_APPS. Let's edit the tutorial/ file:


For the purposes of this tutorial we're going to start by creating a simple Snippet model that is used to store code snippets. Go ahead and edit the snippets/ file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.

from django.db
import models
from pygments.lexers
import get_all_lexers
from pygments.styles
import get_all_styles

LEXERS = [item
   for item in get_all_lexers() if item[1]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()])

class Snippet(models.Model):
   created = models.DateTimeField(auto_now_add = True)
title = models.CharField(max_length = 100, blank = True,
   default = '')
code = models.TextField()
linenos = models.BooleanField(
   default = False)
language = models.CharField(choices = LANGUAGE_CHOICES,
   default = 'python', max_length = 100)
style = models.CharField(choices = STYLE_CHOICES,
   default = 'friendly', max_length = 100)

class Meta:
   ordering = ['created']

Suggestion : 4

You need to use serializers.ModelSerializer not a serializers.Serializer if you are working with models and querysets.,If you are using serializers.Serializer you need to define field in it manually. Like this:, 4 days ago If you want to validate that data during write ops, you'll need to set the field explicitly and set read_only=False. For example, here is a serializer I made that looks much like your EventTypeSerializer: class RedditTestSerializer (serializers.ModelSerializer): class Meta: model = models.Task fields = ("pk",) If we go to shell_plus and print ... , 4 days ago Dec 09, 2021  · Now that you have a file called serializers in your project, let’s create a serializer with DictField as the fields. Python3. from rest_framework import serializers. class Geeks (object): def __init__ (self, dictionary): self.dict = dictionary. class GeeksSerializer (serializers.Serializer): dictionary = serializers.DictField (.

from django.db
import models from django.contrib.auth.models
import User from datetime
import datetime class Staff(models.Model): employer = models.ForeignKey("shops.Shop") user = models.ForeignKey(User) def __unicode__(self): return self.user.username

class StaffSerializer(serializers.Serializer): id = serializers.IntegerField() content = serializers.CharField(max_length = 200)
from django.db
import models from django.contrib.auth.models
import User from datetime
import datetime class Staff(models.Model): employer = models.ForeignKey("shops.Shop") user = models.ForeignKey(User) def __unicode__(self): return self.user.username
from rest_framework
import serializers from staff.models
import Staff class StaffSerializer(serializers.Serializer): class Meta: model = Staff fields = ("id", "employer", "user")
from staff.models
import Staff from staff.serializers
import StaffSerializer from rest_framework
import generics from rest_framework.response
import Response class StaffList(generics.ListCreateAPIView): queryset = Staff.objects.all() serializer_class = StaffSerializerdef list(self, request): queryset = self.get_queryset() serializer = StaffSerializer(queryset, many = True) print queryset print serializer print
return Response(
HTTP 200 OK Content - Type: application / json Vary: Accept Allow: GET, POST, HEAD, OPTIONS[{}]