返回顶部

Django报错UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list

Django报错UnorderedObjectListWarning: Pagination may yield inconsistent results  with an unordered object_list

报错

报错信息如下:

Django报错Django报错UnorderedObjectListWarning: Pagination may yield inconsistent results  with an unordered object_list: <class 'student_check.models.UploadedFile'> QuerySet.

分析

警告是由于Paginator尝试对无序的QuerySet进行分页而引起的。要解决这个问题,你可以在查询时明确指定一个排序规则,例如按照文件上传时间或者文件名进行排序。

解决方案

老代码

@login_required
@rate_limit(20)
def file_list(request):
    if request.user.is_superuser:
        files = UploadedFile.objects.all()
    else:
        files = UploadedFile.objects.filter(user=request.user)  # 仅获取当前用户上传的文件列表
    paginator = Paginator(files, 6)  # 每页显示10个文件

    page = request.GET.get('page')
    try:
        paginated_files = paginator.page(page)
    except PageNotAnInteger:
        paginated_files = paginator.page(1)
    except EmptyPage:
        paginated_files = paginator.page(paginator.num_pages)

    logger.info('用户 {} 访问文件列表'.format(request.user.username))
    return render(request, 'file_list.html', {'files': paginated_files})

新代码

指定文件列表文件以上传时间倒序展示

@login_required
@rate_limit(20)
def file_list(request):
    if request.user.is_superuser:
        files = UploadedFile.objects.all()
    else:
        files = UploadedFile.objects.filter(user=request.user).order_by('-created_at')


    paginator = Paginator(files, 6)  # 每页显示6个文件

    page = request.GET.get('page')
    try:
        paginated_files = paginator.page(page)
    except PageNotAnInteger:
        paginated_files = paginator.page(1)
    except EmptyPage:
        paginated_files = paginator.page(paginator.num_pages)

    logger.info('用户 {} 访问文件列表'.format(request.user.username))
    return render(request, 'file_list.html', {'files': paginated_files})

 

posted @ 2023-12-18 14:40  九尾cat  阅读(230)  评论(0编辑  收藏  举报