Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Haystack - Search on non-indexed many to many field

Is there a way of having only a filtered part of a model as a SeachQuerySet?

Something like:

query = SearchQuerySet().models(Entry.filter(categories__name='something'))

instead of

query = SearchQuerySet().models(Entry)

The field I want to filter by is a manytomany field and non indexed.

like image 925
seda Avatar asked Aug 13 '12 11:08

seda


1 Answers

The search index doesn't store any relations, it is therefore 'flat'. You can only add your categories' IDs to the index for Entry (note that you have to use a prepare_-method for this):

class EntryIndex(indexes.SearchIndex, indexes.Indexable):
    # your other fields
    categories = MultiValueField()

    def prepare_categories(self, obj):
        return [category.pk for category in obj.categories.all()]

The you can do something like:

category = Category.objects.get(name='something')
sqs = SearchQuerySet().models(Entry).filter(categories=category.pk)
like image 199
Bernhard Vallant Avatar answered Sep 24 '22 15:09

Bernhard Vallant