使用django-endless-pagination的过滤器

时间:2013-04-25 17:08:22

标签: django django-endless-pagination jquery-filter

我正在使用Django endles-pagination以无限滚动方式加载页面。我还有一些过滤器根据标准过滤数据(例如,根据价格进行价格滑块过滤)。现在,当页面加载时,过滤器现在只从加载的页面过滤,但我希望它从已经或将要加载的所有页面中过滤它。有没有办法做到这一点(通过制作一些ajax请求或其他东西)?

对此的任何帮助都会很棒。非常感谢。

1 个答案:

答案 0 :(得分:1)

要过滤数据,您必须在请求过滤查询的视图中重新定义get_queryset()方法。

例如,我请求模板中的当前语言根据语言过滤博客帖子:

class Blog(AjaxListView):
    context_object_name = "posts"
    template_name = 'cgapp/blog.html'
    page_template = 'cgapp/post_list.html'

def get_queryset(self):
    if self.request.LANGUAGE_CODE == 'en': #request value of the current language
        return News.objects.filter(language='en') #return filtered object if the current language is English
    else:
        return News.objects.filter(language='uk')

要根据用户输入过滤查询集,可以参考POST方法:

from app.forms import BlogFilterForm

class Blog(LoginRequiredMixin, AjaxListView):
    context_object_name = "posts"
    template_name = 'blog/blog.html'
    page_template = 'blog/post_list.html'
    success_url = '/blog'

    def get_queryset(self): # define queryset
        queryset = Post.objects.all() # default queryset
        if self.request.method == 'POST': # check if the request method is POST
            form = BlogFilterForm(self.request.POST) # define form
            if form.is_valid(): 
                name = form.cleaned_data['name'] # retrieve data from the form
                if name:
                    queryset = queryset.filter(name=name) # filter queryset
        else:
            queryset = queryset
        return queryset 

    def get_context_data(self, **kwargs):
        context = super(Blog, self).get_context_data(**kwargs)
        context['form'] = BlogFilterForm() # define context to render the form on GET method
        return context

    def post(self, request, *args, **kwargs): # define post method
        return super(Blog, self).get(request, args, kwargs)

无尽的分页应该可以正常工作。