Search code examples
pythondjangosolrdjango-haystack

How to config Django-haystack so "content" searched still shows results in the search field


I am using django-haystack-solr and ajax. When a client types in the search field, results matching it dispaly in a drop down box. the thing is solr also searches my content. So if a client types in pasta primavera and its in the content and not the title it doesnt show any result for that. How do I make it so the post title shows even though the query is in the content? To be clear, if I type in pasta primavera and its not a post.title but in the post.content of the post, I still want the post.title to be displayed. What is the correct syntax to get this result? The following is my code

my search_index.py

class PostIndex(indexes.SearchIndex, indexes.Indexable):
        text = indexes.CharField(document=True, use_template=True)
        title = indexes.CharField(model_attr='title')
        content = indexes.CharField(model_attr='content')
        publish = indexes.DateTimeField(model_attr='publish')
        slug = indexes.CharField(model_attr='slug')

        content_auto = indexes.EdgeNgramField(model_attr='title')

        def get_model(self):
            return Post

        def index_queryset(self, using=None):
            """Used when the entire index for model is updated."""
            return self.get_model().objects.all()

my views.py

def search_title(request):
posts = SearchQuerySet().autocomplete(content_auto=request.GET.get('search_text', '')).order_by('-publish')
context = {
    "posts": posts
}
# context.update(csrf(request))
return render(request, "posts/ajax_search.html", {"posts": posts})

my post_text.txt

{{ object.title }}
{{ object.content }}

my ajax_search.html

{% if posts.count > 0 %}
<div class="result-box" id="cell">
{% for post in posts %}

<li><a href="{% url 'posts:detail' post.slug %}" id="fix" class="list-group-item">{{ post.title }}</a></li>
{% endfor %}

{% else %}
<li class="list-group-item" id="none"> None to show</li>

{% endif %}
</div>

all guidance is welcome


Solution

  • This is what worked for me

    sqs = SearchQuerySet()
      sqs1 = sqs.autocomplete(title_auto=query).order_by('-publish')
      sqs2 = sqs.autocomplete(content_auto=query).order_by('-publish')
    
      posts = sqs1 | sqs2