Django-haystack: how to choose which index to use in SearchQuerySet?

I looked at the Haystack documentation for several indexes , but I cannot determine exactly how to use them.

The main model in this example is Proposal. I want to have two search indexes that return a list of offers: one that searches only in the sentences themselves, and one that searches in the sentences along with its comments. I installed search_indexes.pyas follows:

class ProposalIndexBase(indexes.SearchIndex, indexes.Indexable)
    title = indexes.CharField(model_attr="title", boost=1.1)
    text = indexes.NgramField(document=True, use_template=True)
    date = indexes.DateTimeField(model_attr='createdAt')

    def get_model(self):
        return Proposal


class ProposalIndex(ProposalIndexBase):
    comments = indexes.MultiValueField()

    def prepare_comments(self, object):
        return [comment.text for comment in object.comments.all()]


class SimilarProposalIndex(ProposalIndexBase):
    pass

Here is my search in views.py:

def search(request):
    if request.method == "GET":
        if "q" in request.GET:
            query = str(request.GET.get("q"))
            results = SearchQuerySet().all().filter(content=query)
    return render(request, "search/search.html", {"results": results})

How to set up a standalone view that gets a SearchQuerySet from a specific index?

+4
source share
1 answer

Haystack ( ) , , . , , " ", - (, whoosh, solr ..) .

, , , "SearchIndexes" . "" "" + "", .

, API SearchQuerySet, , , . models, , .

, , , "", , "" "" ( ). ( ).

:

/search/?q=python&content=proposal
/search/?q=python&content=everything

, :

# import your model classes so you can use them in your search view
# (I'm just guessing these are what they are called in your project)
from proposals.models import Proposal
from comments.models import Comment

def search(request):
    if request.method == "GET":
        if "q" in request.GET:
            query = str(request.GET.get("q"))
            # Add extra code here to parse the "content" query string parameter...
            # * Get content type to search for
            content_type = request.GET.get("content")
            # * Assign the model or models to a list for the "models" call
            search_models = []
            if content_type is "proposal":
                search_models = [Proposal]
            elif content_type is "everything":
                search_models = [Proposal, Comment]
            # * Add a "models" call to limit the search results to the particular models
            results = SearchQuerySet().all().filter(content=query).models(*search_models)
return render(request, "search/search.html", {"results": results})

( ), , get_model django.db .

+5

All Articles