我正在尝试对搜索查询进行分页。所有进口似乎都在正确的位置,但它一直告诉我这个错误。 “pagination.PaginationSerializer未定义”。我不明白为什么?因为我从“rest_framework.pagination导入PaginationSerializer”导入它。这很奇怪,我确信我正在做一些没有以正确方式完成的事情。所以这是我的代码。
注意:我的代码基于官方文档中的示例。 http://www.django-rest-framework.org/api-guide/pagination#paginating-basic-data
这是我在浏览器中的TraceBack: http://dpaste.com/2R1F03X/
异常类型:/ user-search /
中的NameError异常值:未定义名称“分页” 例外位置:/var/www/api/serializers.py in,第19行
views.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from django.core.paginator import Paginator , EmptyPage, PageNotAnInteger
from django.shortcuts import HttpResponseRedirect
import json
from api.models import users, subjects
from api.serializers import PaginatedUserSerializer, UserKarmaSerializer
@api_view(['GET'])
def user_search(request):
"""
Url must be example (/?subject=iOS Development)
"""
if request.method == 'GET':
search_subject = request.QUERY_PARAMS.get('subject')
# Query
user_ids = subjects.objects.filter(
ss__icontains=search_subject).values('id_user')
user = users.objects.filter(pk__in=user_ids).order_by('-karma', 'rate')
# Pagination Below
paginator = Paginator(user, 20)
page = request.QUERY_PARAMS.get('page')
try:
user = Paginator.page(page)
except PageNotAnInteger:
user = Paginator.page(1)
except EmptyPage:
user = Paginator.page(Paginator.num_pages)
serializer_context = {'request': request}
serializer = PaginatedUserSerializer(user,context=serializer_context)
return Response(serializer.data, status=status.HTTP_200_OK)
serializers.py
from rest_framework import serializers
from rest_framework.pagination import PaginationSerializer
from api.models import users, chat, call, subjects
""" Search Tutors Based on Rate & Subjects """
# Below is line 19
class UserSearchSerializer(serializers.HyperlinkedModelSerializer):
subjects = serializers.Field(source='user_subjects')
user_rate = serializers.Field(source='rate_format')
class Meta:
model = users
fields = ('name', 'nick', 'avatar_s', 'user_rate', 'id', 'subjects', 'bio', 'experience')
class PaginatedUserSerializer(pagination.PaginationSerializer):
class Meta:
object_serializer_class = UserSearchSerializer
答案 0 :(得分:2)
因为您将其导入为PaginationSerializer,所以前面不需要分页。改为:
class PaginatedUserSerializer(PaginationSerializer)
或者,您可以更改导入:
from rest_framework import pagination