Search code examples
pythondjangodjango-haystack

Exclude objects on Haystack search without the need of update_index


I need Haystack search to exclude some objects with value published=False, the way I've managed it so far is by adding an exclude(published=True) as following:

class MymodelIndex(indexes.RealTimeSearchIndex, indexes.Indexable):
    def get_queryset(self):
        return Mymodel.objects.all().exclude(published=False)

It works as expected, the problem is that I need to ./manage.py rebuild_index everytime a new object is added to the database which makes it terrible.

How can I make it without the need to run anything else ?

Notes:

Indexes on Haystack work for many models, so something like this:

search = (
    SearchQuerySet().filter(content=term)
)

returns many kinds of objects and not just one model.

Thanks


Solution

  • Thanks to @SI Eric, I was able to find an answer, it's also kinda hacky but it works.

    search = (
        SearchQuerySet().filter(content=term)
    )
    
    search_list = search[:]
    unpublished_Mymodels = Mymodel.objects.filter(published=False)
    
    for match in search_list:
        try:
            if match.model_name == 'Mymodel':
                if match._get_object() in unpublished_Mymodels:
                    search_list.remove(match)
        except:
            pass
    
    search = search_list