我有一个django Listview,我正在使用django-el-pagination&ajax ajax无尽的分页来分页我的结果,它运作良好。问题是我需要对它应用一些过滤器,并且不知道如何做到这一点。
我可以通过GET将参数发送到视图吗?已经搜索了很多,似乎以前没有人遇到过这个问题。
答案 0 :(得分:0)
始终在get_queryset()
函数中返回数据。
如果您只想从数据库中过滤,只需返回对象即可。
class IndexView(AjaxListView):
template_name = '****'
context_object_name = '****'
page_template = '****'
def get_queryset(self):
return your_model.objects.filter(title='***').order_by('**')
否则,如果您想从非数据库获取数据,则需要根据this answer实现代理。
如果没有,分页ajax将请求所有数据,然后将其切片。代理会在查询时切换数据。
这是我从ElasticSearch获取数据的过滤器。
class IndexView(AjaxListView):
template_name = '****'
context_object_name = '****'
page_template = '****'
def get_queryset(self):
params = {}
# get query params
for item in self.request.GET.items():
if item[0] == 'page' or item[0] == 'querystring_key':
continue
params[item[0]] = item[1]
# no filter
if len(params) == 0:
return ****.objects.filter().order_by('-date')
else:
return ESResult(params)
class ESResult(object):
def __init__(self, params):
self.params = params
def __len__(self):
s = self.search_es()
if s:
s = s[:1]
r = s.execute()
return r['hits']['total']
else:
return 0
def __getitem__(self, item):
assert isinstance(item, slice)
result = []
s = self.search_es()
if s:
s = s[item.start:item.stop] # slice before querying
r = s.execute()
for a in r.to_dict()['hits']['hits']:
one = a['_source']
one['id'] = int(a['_id'])
result.append(one)
return result
def search_es():
...
# filter request here
...
答案 1 :(得分:-1)
AjaxListView使用的列表对象由get_queryset()
方法定义。要根据用户输入过滤查询集,可以参考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)
无尽的分页应该可以正常工作。 using filters with django-endless-pagination