I'm following this tutorial (Django Rest Framework) and I'm facing a problem when I try to use serializers. It returns a empty result, instead the 49086 records that it should to return. My query it's ok because when I try to show the data without serializers it's shows these data. Please, what I'm doing wrong?
models.py
# coding=utf-8
from __future__ import unicode_literals
from django.db import models
class Workers(models.Model):
chapa = models.IntegerField(primary_key=True)
emp_cod = models.IntegerField(primary_key=False)
class Meta:
managed = False
db_table = 'WORKERS'
serializers.py
from rest_framework import serializers
from .models import Workers
class WorkersSerializer(serializers.ModelSerializer):
class Meta:
model = Workers
fields = '__all__'
views.py
...
@api_view(['GET'])
@permission_classes((permissions.AllowAny,))
def get_all_workers(request):
data = Workers.objects.using('rh').all().order_by('emp_cod')
print(data.count()) # Returns 49086
serializer = WorkersSerializer(data)
print(serializer.data) # Returns {}
json = JSONRenderer().render(serializer.data)
return Response(json) # Returns Django Rest standard page with "{}" data
You should use many=True serializer's argument to serialize multiple objects. Also you can pass serializer.data directly as Response argument:
@api_view(['GET'])
@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(serializer.data)
Since your view return so many objects at once, I suggest you to add pagination:
from rest_framework.pagination import PageNumberPagination
@api_view(['GET'])
@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(serializer.data)
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