Login

Haystack objects in one query

Author:
jasisz
Posted:
October 13, 2011
Language:
Python
Version:
1.3
Tags:
django haystack SearchQuerySet
Score:
0 (after 0 ratings)

Actually the best way to handle this is to use built-in http://docs.haystacksearch.org/dev/searchqueryset_api.html#load-all

I just missed it while checking documentation and wrote this crappy snippet!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def haystack_monkey_load(sqs):
    """
    it loads all Items for given SearchQuerySet and attaches them as "object" in each SearchResult
    """
    model_dict = {'app.item': Item, 'another_app.comment': Comment}
    for model_key, model in model_dict.items():
        items_id = [sr.pk for sr in sqs if sr.app_label+"."+sr.model_name == model_key]
        items = model.objects.filter(id__in=items_id).select_related()
        for item in items:
            for sr in sqs:
                if item.id == sr.pk and sr.app_label+"."+sr.model_name == model_key:
                    sr.object = item
    return sqs


class SpecialSearchView(SearchView):
    def build_page(self):
        """ for example special SearchView that uses haystack_monkey_load for pagination """
        paginator = paginator(self.results, self.results_per_page)
        try:
            page = paginator.page(self.request.GET.get('page', 1))
            page.object_list = haystack_monkey_load(page.object_list)
        except InvalidPage:
            raise Http404
        return (paginator, page)

More like this

  1. Haystack whoosh backend for stemming non-english language words by shamakhov 1 year, 6 months ago
  2. haystack auto update (forget about update_index) by jpic 3 years, 7 months ago
  3. Format Haystack's result with a sprat template by myles 6 years, 2 months ago
  4. plaintext filter by onelson 5 years, 4 months ago
  5. . by jeremydw 5 years ago

Comments

Please login first before commenting.