Reputation: 2403
I am trying to use Haystack/Whoosh search with Django Tables 2. The search results should be rendered as table. This is my current view for rendering the tables:
def people(request):
table = PersonTable(Person.objects.filter(pk=1))
RequestConfig(request).configure(table)
return render(request, 'people.html', {'table': table})
Haystack should pass the primary keys of search results to the above view function like so Person.objects.filter(pk=va1,pk=var2)
so this view function can display the results.
I was able to write a working view:
def report(request, template='report.html', load_all=True, form_class=ModelSearchForm, searchqueryset=None, context_class=RequestContext, extra_context=None, results_per_page=None):
table = ''
query = ''
results = EmptySearchQuerySet()
if request.GET.get('q'):
form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all)
if form.is_valid():
query = form.cleaned_data['q']
results = form.search()
pklist = [ r.pk for r in results ]
table = PersonTable(Person.objects.filter(pk__in=pklist))
RequestConfig(request).configure(table)
else:
form = form_class(searchqueryset=searchqueryset, load_all=load_all)
context = {
'form': form,
'table': table,
}
return render_to_response(template, context, context_instance=context_class(request))
It works somehow. However, as I'm just a Django beginner, I feel that there is scope for improvement. I posted it here so as to get some useful suggestions.
Upvotes: 0
Views: 961
Reputation: 1163
Presuming that creating your PersonTable
instance with a SearchQuerySet
is not an option, you could try passing a list of the Person
objects from your search.
def search(request):
# Let's say there's some logic here for querying your search engine
# using Haystack, and `results` is a SearchQuerySet of Person results
table = PersonTable([result.object for result in results])
RequestConfig(request).configure(table)
return render(request, 'people.html', {'table': table})
Otherwise your problem statement that you need to pass the primary keys of the results to the view function is a little unclear.
Upvotes: 1