我有一个奇怪的问题。我有一个视图,它通过 Django REST Framework 的序列化程序和分页器返回一些 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_ids 参数调用 URL。它给出了一个错误:global name 'PageNotAnInteger' is not defined
引用 then 异常。
我的代码有问题吗?为什么 PageNotAnInteger 在更改查询集之前会起作用 find 是没有意义的。