Django对页面限制的分页显示仍然是最后的结果无休止

时间:2017-12-28 15:48:29

标签: django pagination django-rest-framework django-queryset serializer

我有一个基于Django函数的API,它输入页码,每页都有页面大小。这是我的代码。

@api_view(['POST'])
def attendance_all_get_list_by_page(request):
    # ----- YAML below for Swagger -----
    """
    description: attendance_all_get_list_by_page
    parameters:
      - name: page
        type: integer
        required: true
        location: form   
      - name: page_limit
        type: integer
        required: true
        location: form                   
    """
    attendance_list = Attendance.objects.all().order_by('id') 

    page = request.GET.get('page', request.POST['page'])
    paginator = Paginator(attendance_list, request.POST['page_limit'])

    try:
        attendances = paginator.page(page)
    except PageNotAnInteger:
        attendances = paginator.page(request.POST['page'])
    except EmptyPage:
        attendances = paginator.page(paginator.num_pages)


    serializer = AttendanceSerializer(list(attendances), many=True)
    data = serializer.data[:]
    return Response(data, status=status.HTTP_200_OK)  

我的序列化器:

class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = ("id", "username")

class AttendanceSerializer(serializers.ModelSerializer):
    employee = EmployeeSerializer(many=False, read_only=True)

    class Meta:
        model = Attendance
        fields = ('id','employee','created_at')

想象一下,我有

的出勤记录
16,17,18,19

例如,如果页面= 2 page_limit = 2,它将显示以下内容(这应该是4条记录的最后一页)

[
  {
    "id": 18,
    "employee": {
      "id": 16,
      "username": "haha"
    },
    "created_at": "2017-12-28T03:29:29.698339Z"
  },
  {
    "id": 19,
    "employee": {
      "id": 16,
      "username": "haha"
    },
    "created_at": "2017-12-28T03:38:53.639749Z"
  }
]

如果我这样做(page = 3 page_limit = 2)或(page = 10 page_limit = 2),它仍会显示

[
  {
    "id": 18,
    "employee": {
      "id": 16,
      "username": "haha"
    },
    "created_at": "2017-12-28T03:29:29.698339Z"
  },
  {
    "id": 19,
    "employee": {
      "id": 16,
      "username": "haha"
    },
    "created_at": "2017-12-28T03:38:53.639749Z"
  }
]

预期结果应为

[]

我的分页错误,在最后一页影响了一些东西。我希望最后一页显示最后一页的结果,但之后应该是空记录列表。

1 个答案:

答案 0 :(得分:0)

您捕获EmptyPage并返回最后一页内容。因此,如果您超出范围,您将每次都获得第二页。 在这种情况下,您需要返回空列表:

except EmptyPage:
    attendances = []