我该如何对以下视图进行分页

时间:2019-02-04 10:18:01

标签: django django-models django-forms django-templates django-views

我想分页关注UserListView

class UserListView(LoginRequiredMixin, generic.TemplateView):
    template_name = 'users/users.html'
    paginate_by = 1

    def get_context_data(self, **kwargs):   
        context = super(UserListView, self).get_context_data(**kwargs)
        context['companies'] = Company.objects.exclude(company_is_deleted=True).exclude(company_name='Apollo')
        context['users'] = User.objects.filter(userprofile__user_role__id=2).exclude(
            Q(is_superuser=True) | 
            Q(userprofile__user_is_deleted = True)|
            Q(userprofile__user_company__company_is_deleted=True)
            )
        query = self.request.GET.get('query') 
        if query:
            list_query = context['users']
            context['users'] = list_query.filter(userprofile__user_company__company_name__icontains=query)
        return context

1 个答案:

答案 0 :(得分:1)

class UserListView(LoginRequiredMixin, generic.ListView):
    template_name = 'users/users.html'
    paginate_by = 1
    context_object_name = 'users'

    def get_queryset(self, *args, **kwargs):
        qs = User.objects.filter(userprofile__user_role__id=2).exclude(
        Q(is_superuser=True) | 
        Q(userprofile__user_is_deleted = True)|
        Q(userprofile__user_company__company_is_deleted=True)
        )
        query = self.request.GET.get('query') 
        if query:
            qs = qs.filter(userprofile__user_company__company_name__icontains=query)

        return qs
    def get_context_data(self, **kwargs):   
        context = super(UserListView, self).get_context_data(**kwargs)
        context['companies'] = Company.objects.exclude(company_is_deleted=True).exclude(company_name='Apollo')
        return context

如果您需要自定义分页,则应查看docs