Login

Haystack objects in one query

Author:
jasisz
Posted:
October 13, 2011
Language:
Python
Version:
1.3
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.