Search code examples
pythondjangodjango-haystack

Queryset Filter If Overlap in Lists


I have a MultiValueField in my index containing a list of specialties for a given provider. In my search, I want to allow users to select specialties to filter by, filtering out any providers that do not match at least one specialty with the selected specialties. Essentially I want all providers who have any overlap in specialties with the selected filters.

For example If:

Guido specializes in Python, C and Unix

James specializes in Java, Unix, and Compilers

Bill specializes Windows and C

And I select filters Python and Windows, I want to see Guido and Bill. If I select filters C and Compilers, I want to see Guido, James and Bill. Etc. etc.

Here is my search_indexes.py

class ProviderIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    specialties = indexes.MultiValueField(model_attr='specialties_as_list')

And my form has

specialities = forms.MultipleChoiceField(widget=CheckboxSelectMultiple(), choices=Provider.SPECIALTY_CHOICES)

as the field for specialties.

EDIT

For anyone not familiar with Haystack, the queries work essentially the same as the django ORM, so you can still help! A MultiValueField is stored in the index as a json array of strings, essentially a Python List for our purposes. Is there any way to write a queryset to check if any intersection exists between 2 lists?


Solution

  • Simple 'in' filter did the job... I feel dumb that this stumped me for so long.

    sqs = sqs.filter(specialties__in=self.cleaned_data['specialties'])