Skip to main content
 首页 » 编程设计

python之使用 Django-Rest 排序游标分页

2024年10月24日33lyj

我正在使用 Django-Rest-Framework 构建一个 API 并设置光标分页 - 默认情况下按“已创建”过滤器排序,这对某些 View 非常有效。

但我有这个,我想按其他字段(last_update 和访问)排序。我将订购字段放在我的 View 中,但不起作用。

class StationList(generics.ListAPIView): 
 
    """ 
    List all stations. 
    """ 
    ordering = ('-last_update', '-visits',) 
    queryset = Station.objects.all() 
    serializer_class = StationSerializer 
    permission_classes = (permissions.IsAuthenticated,) 

那是我setting.py的一部分

REST_FRAMEWORK = { 
    'DEFAULT_RENDERER_CLASSES': ( 
        'rest_framework.renderers.JSONRenderer', 
    ), 
    'DEFAULT_AUTHENTICATION_CLASSES': ( 
        'rest_framework.authentication.SessionAuthentication', 
        'rest_framework.authentication.TokenAuthentication', 
    ), 
    'DEFAULT_PERMISSION_CLASSES': ( 
        'rest_framework.permissions.AllowAny', 
    ), 
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', 
    'PAGE_SIZE': 12, 
} 

我需要做什么才能让它起作用?

请您参考如下方法:

也尝试在 ordering_fields 下列出您的字段,我认为您仍然需要将它们列入白名单以进行排序:

ordering = ('-last_update', '-visits',) 
ordering_fields= ('-last_update', '-visits',)