Django Rest Serializer返回空

时间:2018-05-18 14:12:10

标签: python django python-3.x serialization django-rest-framework

我遵循本教程(Django Rest Framework),当我尝试使用序列化程序时,我遇到了问题。它返回一个空结果,而不是它应该返回的49086条记录。我的查询没问题,因为当我尝试在没有序列化程序的情况下显示数据时,它会显示这些数据。请问,我做错了什么?

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

1 个答案:

答案 0 :(得分:3)

您应该使用many=True序列化程序的参数来序列化多个对象。您也可以直接将serializer.data作为Response参数传递:

@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)

由于您的视图一次返回了这么多对象,我建议您添加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)