我有个奇怪的问题。我有一个视图,它通过django rest框架中的序列化器和分页器返回一些json。
我的视图如下(返回国家/地区模型中的所有对象):
@api_view(['GET'])
def country_list(request):
"""
List all countries
"""
if request.method == 'GET':
geoname_ids = request.QUERY_PARAMS.get('geoname_ids')
queryset = Countries.objects.all()
paginator = Paginator(queryset, request.QUERY_PARAMS.get('limit'))
page = request.QUERY_PARAMS.get('page')
try:
countries = paginator.page(page)
except PageNotAnInteger:
#If page is not an integer, deliver first page.
countries = paginator.page(1)
except EmptyPage:
#If page is out of range
#Delivery last page of results
countries = paginator.page(paginator.num_pages)
serializer_context = {'request': request}
serializer = PaginatedCountrySerializer(countries, context=serializer_context)
return Response(serializer.data)
这很管用。
不过,我需要返回一个具有特定ID的国家,我正在尝试:
@api_view(['GET'])
def country_list(request):
"""
List all countries
"""
if request.method == 'GET':
geoname_ids = request.QUERY_PARAMS.get('geoname_ids')
queryset = Countries.objects.filter(country_geoname_id=geoname_ids)
paginator = Paginator(queryset, request.QUERY_PARAMS.get('limit'))
page = request.QUERY_PARAMS.get('page')
try:
countries = paginator.page(page)
except PageNotAnInteger:
#If page is not an integer, deliver first page.
countries = paginator.page(1)
except EmptyPage:
#If page is out of range
#Delivery last page of results
countries = paginator.page(paginator.num_pages)
serializer_context = {'request': request}
serializer = PaginatedCountrySerializer(countries, context=serializer_context)
return Response(serializer.data)
很明显,我用geonames\uids参数调用url。它给出了一个错误:
global name 'PageNotAnInteger' is not defined
引用then异常。我的代码有问题吗?在更改queryset之前,pagenotainteger为什么要先找到工作,这是不合理的。
最佳答案
您应该先导入它:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger