Greg Hinch
Greg Hinch

Reputation: 827

How do I query for empty MultiValueField results in Django Haystack

Using Django 1.4.2, Haystack 2.0beta, and ElasticSearch 0.19, how do I query for results which have an empty set [] for a MultiValueField?

Upvotes: 1

Views: 623

Answers (2)

Yaroslav Varkhol
Yaroslav Varkhol

Reputation: 957

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)

Upvotes: 0

Marcel Chastain
Marcel Chastain

Reputation: 2131

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)

Upvotes: 2

Related Questions