2016-09-28 170 views
0

我是一個非常喜歡django-haystack的新手。遵循文檔和教程,我能夠基於文檔內容(DataBase SQLITE)創建搜索應用程序。下一步,我已經更新了我的HTML模板以請求更多信息(例如:模型,所需的數據庫鏈接等)。Django-Haystack根據多個索引字段進行搜索

我不知道如何解決這個問題。在我正在使用的文件下面。我的知識還是很基礎的,所以任何幫助都會非常感激。

謝謝。

search.html

{% extends 'base.html' %} 

{% block content %} 


    <h2> Doc Search Interface</h2> 

    <form method="get" action="."> 
     <table> 
      <P>Select Car Model:</P> 
      <P><LABEL ACCESSKEY=5><INPUT TYPE=checkbox NAME="CarModel" VALUE="A5"> A5</LABEL><BR> 
      <LABEL ACCESSKEY=8><INPUT TYPE=checkbox NAME="CarModel" VALUE="A8"> A8</LABEL><BR> 
      <LABEL ACCESSKEY=3><INPUT TYPE=checkbox NAME="CarModel" VALUE="A3"> A3</LABEL></P> 

      <tr> 
      <P>Type and click enter for Search!</P> 
       <input type="search" id="id_q" name="q" placeholder="Search" > 
      </tr> 
     </table> 

     {% if query %} 
      <h3>Let´s see if we have got here the document you were looking for...</h3> 

      {% for result in page.object_list %} 
       <p> 
        <a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a> 
       </p> 
      {% empty %} 
       <p>No results found.</p> 
      {% endfor %} 

      {% if page.has_previous or page.has_next %} 
       <div> 
        {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %} 
        | 
        {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %} 
       </div> 
      {% endif %} 
     {% else %} 
      {# Show some example queries to run, maybe query syntax, something else? #} 
     {% endif %} 
    </form> 
{% endblock %} 

models.py

from django.db import models 
from django.contrib.auth.models import User 
from django.template import RequestContext 
from django.http import HttpResponse 

class Document(models.Model): 

user_id = models.CharField(max_length=6, default='admin') 
pub_date = models.DateTimeField() 
title = models.CharField(max_length=200) 
Link= models.URLField() 
content = models.TextField() 
CarModel= models.TextField() 

    def get_absolute_url(self): 
     return self.Link 
    def __unicode__(self): 
     return self.title 

search_indexes.py

from haystack import indexes 
from test3.models import Document 

class DocumentIndex(indexes.SearchIndex, indexes.Indexable): 
    text = indexes.EdgeNgramField(document=True, use_template=True) 
    content_auto=indexes.EdgeNgramField(model_attr='content') 
    CarModel=indexes.EdgeNgramField(model_attr='CarModel') 
    def get_model(self): 
     return Document   
    def index_queryset(self, using=None): 
     """Used when the entire index for model is updated. Typically to avoid some results showing when admin do not want to""" 
     return self.get_model().objects 

繼THI S以外職位Using django haystack search with global search bar in template我有以下文件

urls.py更新

from django.conf.urls import url 
from test3.views import MySearchView 


# urls.py 

urlpatterns = [url(r'^/search/?$', MySearchView.as_view(), name='My_search_view'),] 

views.py

from haystack.forms import HighlightedSearchForm 
from haystack.query import SearchQuerySet 
from haystack.generic_views import SearchView 
from haystack.views import search_view_factory 

class MySearchView(SearchView): 
    """My custom search view.""" 
    def search_posts(request): 
     post_type = str(request.GET.get('CarModel')).lower() 
     print (str(request.GET.get('CarModel')).lower()) 
     sqs = SearchQuerySet().filter(CarModel__contains=post_type) 
     clean_query = sqs.query.clean(post_type) 
     result = sqs.filter(content=clean_query) 
     view = search_view_factory(
      view_class=SearchView, 
      template='search/search.html', 
      searchqueryset=result, 
      form_class=HighlightedSearchForm 
      ) 
     return view(request) 

但是,我還是沒能工作...搜索結果仍未被'模型'字段過濾。我想我必須添加額外的代碼,但我不知道在哪裏...

+0

簡而言之,我想要修改我的代碼,以便我可以在文檔內容字段上執行查詢(只獲取文檔中的文檔,這些文檔也具有從HTML文件中複選框中取得的值作爲模型字段的值) – fpereira

回答

0

我會盡力迴應。這是我如何得到它的工作:

yourapp/urls.py

url(r'^search/$', views.search_notes, name='search_notes'), 

yourapp/views.py導入NotesSearchForm(下文進一步),並調用搜索:

from .forms import NotesSearchForm 

def search_notes(request): 
    form = NotesSearchForm(request.GET) 
    notes = form.search() 
    return render_to_response('notes/index.html', {'notes': notes, 'form': form}) 

    context = { 'latest_notes_list': latest_notes_list} 
    return render(request, 'notes/index.html', context) 

然後在你的yourapp/forms.py就是魔法發生:

from haystack.forms import SearchForm 

class NotesSearchForm(SearchForm): 

    # First we add the form fields, in your case BooleanFields. 
    sports = forms.BooleanField() 
    fiction = forms.BooleanField() 
    non_fiction = forms.BooleanField() 


    def search(self): 
     # Here we store the SearchQuerySet received from other processing. 
     sqs = super(NotesSearchForm, self).search() 

     if not self.is_valid(): 
     return self.no_query_found() 

     # Then filter your results when the search come back 

     if self.cleaned_data['sports']: 
     sqs = sqs.filter(genre='sports') 
     if self.cleaned_data['fiction']: 
     sqs = sqs.filter(genre='fiction') 
     if self.cleaned_data['non_fiction']: 
     sqs = sqs.filter(genre='non_fiction') 

     return sqs 

    def no_query_found(self): 
     # This we add to make all results show if nothing is selected or searched for (optional) 
     return self.searchqueryset.all() 

請注意,在這裏我把'流派'作爲字段在您的模型中的名稱。該場還需要存在於你的search_indexes.py,像這樣:

genre = indexes.CharField(model_attr='genre') 

最後,讓我告訴你的yourapp /模板/筆記/ index.html的

<!-- Form here --> 
{{ form }} 

<!-- Search results here --> 
{% for note in notes %} 

    {{ note.object.title }} 
    {{ notes.object.body|linebreaks }}"> 

{% endfor %} 

希望它適合你!讓我知道如果你卡住了。