Using django haystack search with global search bar in template

柔情痞子 提交于 2020-01-05 08:12:35

问题


I have a django project that needs to search 2 different models and one of the models has 3 types that I need to filter based on. I have haystack installed and working in a basic sense (using the default url conf and SearchView for my model and the template from the getting started documentation is returning results fine).

The problem is that I'm only able to get results by using the search form in the basic search.html template and I'm trying to make a global search bar work with haystack but I can't seem to get it right and I'm not having a lot of luck with the haystack documentation. I found another question on here that led me to the following method in my search app.

my urls.py directs "/search" to this view in my search.views:

def search_posts(request):
    post_type = str(request.GET.get('type')).lower()
    sqs = SearchQuerySet().all().filter(type=post_type)
    view = search_view_factory(
        view_class=SearchView,
        template='search/search.html',
        searchqueryset=sqs,
        form_class=HighlightedSearchForm
        )
    return view(request)

The url string that comes in looks something like:

http://example.com/search/?q=test&type=blog

This will get the query string from my global search bar but returns no results, however if I remove the .filter(type=post_type) part from the sqs line I will get search results again (albeit not filtered by post type). Any ideas? I think I'm missing something fairly obvious but I can't seem to figure this out.

Thanks, -Sean

EDIT:

It turns out that I am just an idiot. The reason why my filtering on the SQS by type was returning no results was because I didn't have the type field included in my PostIndex class. I changed my PostIndex to:

class PostIndex(indexes.SearchIndex, indexes.Indexable):
      ...
      type = indexes.CharField(model_attr='type')

and rebuilt and it all works now.

Thanks for the response though!


回答1:


def search_posts(request):
    post_type = str(request.GET.get('type')).lower()
    sqs = SearchQuerySet().filter(type=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)


来源:https://stackoverflow.com/questions/15491524/using-django-haystack-search-with-global-search-bar-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!