2015-06-30 67 views
0

使用Django/Haystack/SOLR,我希望能夠將搜索結果限制在django_ids特定範圍內的那些記錄。獲取這些ID不是問題,但試圖通過它們進行篩選會產生一些意想不到的效果。代碼如下所示(爲清晰起見,修剪了外部代碼):過濾乾草堆(SOLR)結果django_id

def view_results(request,arg): 
    # django_ids list is first calculated using arg... 
    sqs = SearchQuerySet().facet('example_facet') # STEP_1 
    sqs = sqs.filter(django_id__in=django_ids) # STEP_2 

    view = search_view_factory(
     view_class=SearchView, 
     template='search/search-results.html', 
     searchqueryset=sqs, 
     form_class=FacetedSearchForm 
    ) 

    return view(request) 

在標記爲STEP_1的位置,我獲取了所有數據庫記錄。在STEP_2中,記錄成功縮小到我對django_ids列表的期望數量。在用戶在表單中指定搜索詞的情況下顯示搜索結果時出現問題。我沒有返回與STEP-2匹配的所有記錄,而是從STEP_2中獲取所有記錄,並從STEP_1中獲取與該術語匹配的所有記錄。

因此,大概我需要在haystack/views.py中重寫SearchView中的一個/一些方法,但是什麼?任何人都可以提出一種實現這裏所需要的方法嗎?

回答

0

經過一番思考,我找到了解決辦法。在上面的代碼中,問題出現在view = search_view_factory...行中,因此我需要創建自己的SearchView類並覆蓋get_results(self)方法,以便在用用戶搜索條件運行搜索之後應用篩選。其結果是沿着這些線路代碼:

class MySearchView(SearchView): 

    def get_results(self): 
     search = self.form.search() 
     # The ID I need for the database search is at the end of the URL, 
     # but this may have some search parameters on and need cleaning up. 
     view_id = self.request.path.split("/")[-1] 
     view_query = MyView.objects.filter(id=view_id.split("&")[0]) 

     # At this point the django_ids of the required objects can be found. 
     if len(view_query) > 0: 
      view_item = view_query.__getitem__(0) 
      django_ids = [] 
      for thing in view_item.things.all(): 
       django_ids.append(thing.id) 
      search = search.filter_and(django_id__in=django_ids) 
     return search 

使用search.filter_and而非search.filter末是這竟然是必不可少的另一件事,但沒有做什麼,我需要的時候得到之前執行的濾波到SearchView。