我有一个奇怪的问题。我有一个视图,它通过Django REST Framework中的序列化程序和分页器返回一些JSON。
我的视图如下所示(返回Countries模型中的所有对象):
@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_ids参数调用了这个URL。它给出了一个错误:global name 'PageNotAnInteger' is not defined
引用了那个异常。
我的代码有问题吗?在更改查询集之前,为什么PageNotAnInteger可以找到它是没有意义的。
答案 0 :(得分:9)
您应该先导入它:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
答案 1 :(得分:1)
如果不导入PageNotAnInteger,则无法使用它。 因此,请先导入它。
from django.core.paginator import PageNotAnInteger
如果您还需要EmptyPage:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger