我正在尝试对所有api调用进行默认分页:
http://www.django-rest-framework.org/api-guide/pagination/#modifying-the-pagination-style
现在我想让我的CustomPagination
全球工作:
class CustomPagination(PageNumberPagination):
"""
自定义分页器
"""
page_size = 10
page_size_query_param = 'page_size'
max_page_size = 1000
我希望将类注册到settings.py
:
# =========== REST Framework ==============
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'football.views.CustomPagination',
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',),
}
但是,它引发了一个错误:
ImportError:无法为API设置'DEFAULT_PAGINATION_CLASS'导入'football.views.CustomPagination'。 AttributeError:module'football.views'没有属性'CustomPagination'。
我该如何解决它?
答案 0 :(得分:0)
我遇到了同样的问题,最后我发现它是因为模块views.py
未正确加载,因为我没有manage.py startapp
创建其余的api文件夹而且没有项目INSTALLED_APPS
文件setting.py
中的项目。
我将CustomPagination
分页类移动到views.py
创建的第一个应用程序的manage.py startapp
,然后就可以了。
要进行调试,您可以将以下行添加到rest_framework/settings.py source code,如下所示:
module = import_module(module_path) # Original code
if (setting_name == "DEFAULT_PAGINATION_CLASS"): # Added code
print(dir(module)) # Added code
return getattr(module, class_name) # Original code
如果引发AttributeError
,它应该是:(仅列表中的内置属性)
# ./manage.py runserver 0:8000 Performing system checks... ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] Unhandled exception in thread started by .wrapper at 0x7fd60a265510> Traceback (most recent call last):
如果有效,CustomPagination
应列在列表中:
# ./manage.py runserver 0:8000 Performing system checks... ['some-other-classes', 'PageNumberPagination', 'CustomPagination', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'models', 'random', 'reverse', 'settings'] System check identified no issues (0 silenced).