Filter Django Haystack results like QuerySet?

nikola picture nikola · Jan 29, 2010 · Viewed 8.5k times · Source

Is it possible to combine a Django Haystack search with "built-in" QuerySet filter operations, specifically filtering with Q() instances and lookup types not supported by SearchQuerySet? In either order:

haystack-searched -> queryset-filtered

or

queryset-filtered -> haystack-searched

Browsing the Django Haystack documentation didn't give any directions how to do this.

Answer

ar0n picture ar0n · Jun 14, 2010

You could filter your queryset based on the results of a Haystack search, using the objects' PKs:

def view(request):
  if request.GET.get('q'):
    from haystack import ModelSearchForm
    form = ModelSearchForm(request.GET, searchqueryset=None, load_all=True)
    searchqueryset = form.search()
    results = [ r.pk for r in searchqueryset ]

    docs = Document.objects.filter(pk__in=results)
    # do something with your plain old regular queryset

    return render_to_response('results.html', {'documents': docs});

Not sure how this scales, but for small resultsets (a few hundred, in my case), this works fine.