[Answer]-How do I query for empty MultiValueField results in Django Haystack

1👍

I’d create an integer field named num_<field> and query against it.

In this example ’emails’ is the MultiValueField, so we’ll create ‘num_emails’:

class PersonIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    name = indexes.CharField(model_attr='name')
    emails = indexes.MultiValueField(null=True)
    num_emails = indexes.IntegerField()

    def prepare_num_emails(self, object):
        return len(object.emails)

Now, in your searches you can use

SearchQuerySet().filter(num_emails=0)

0👍

You can also change prepare_ method of your MultiValueField:

def prepare_emails(self, object):
    emails = [e for e in object.emails]
    return emails if emails else ['None']

Then you can filter:

SearchQuerySet().filter(emails=None)

Leave a comment