Django分页功能警告:UnorderedObjectListWarning: Pagination may yield inconsistent results...

在views.py中会出现如下警告:
UnorderedObjectListWarning: Pagination may yield inconsistent results…

class UserListView(View):
    """
    用户列表视图
    """

    def get(self, request):
        '''
        用户列表:
            - 接收参数
            - 校验参数
            - 查询数据
            - 分页
        '''
        user_queryset = User.objects.only('username', 'is_active', 'mobile', 'is_staff', 'is_superuser').order_by('id')
        groups = Group.objects.only('name').all()   
        query_dict = {}
        # 校验参数
        # 校验是否为超级用户:
        groups__id = request.GET.get('group')
        if groups__id:
            try:
                groups__id = int(groups__id)
                query_dict['groups__id'] = groups__id
            except Exception as e:
                pass

        is_staff = request.GET.get('is_staff')
        if is_staff == '0':
            query_dict['is_staff'] = False
        if is_staff == '1':
            query_dict['is_staff'] = True

        is_superuser = request.GET.get('is_superuser')
        if is_superuser == '0':
            query_dict['is_superuser'] = False
        if is_superuser == '1':
            query_dict['is_superuser'] = True

        username = request.GET.get('username')

        if username:
            query_dict['username'] = username

        try:
            page = int(request.GET.get('page', 1))
        except Exception as e:
            page = 1

        paginater = Paginator(user_queryset.filter(**query_dict), 2)

        users = paginater.get_page(page)
        context = {
            'users': users,
            'groups': groups
        }
        context.update(query_dict)
        return render(request, 'myadmin/user/user_list.html', context=context)

注意:在取数据的时候要排序,上述示范视图中的此行代码:
user_queryset = User.objects.only(‘username’, ‘is_active’, ‘mobile’, ‘is_staff’, ‘is_superuser’).order_by(‘id’)
数据查询出来后使用.order_by(‘id’)排序!
不然就会出现上述警告。

上一篇:java之redis篇(spring-data-redis整合)


下一篇:视频在 H5 游戏中的应用