首页 > 其他分享 >Django报错UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered obj

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

时间:2023-12-18 14:44:21浏览次数:37  
标签:files paginator Pagination paginated may list request 报错 page

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})

 

标签:files,paginator,Pagination,paginated,may,list,request,报错,page
From: https://www.cnblogs.com/weiweirui/p/17911191.html

相关文章