Search code examples
pythondjangofilterdjango-haystackwhoosh

Haystack SearchQuerySet won't filter on a CharField with one character (Whoosh / django-haystack)


I'm using Django 1.5.1 with django-haystack 2.1.0 and the whoosh 2.5.2 backend:

models.py:

GENDER_CHOICES = (
    (u'M', u'Male'),
    (u'F', u'Female'),
)

class Applicant(models.Model):

    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    first_name = models.CharField(max_length=64)
    last_name = models.CharField(max_length=64)

search_indexes.py:

class ApplicantIndex(indexes.SearchIndex, indexes.Indexable):

    text = indexes.CharField(document=True,use_template=True)
    gender = indexes.CharField(model_attr="gender")

search template

{{ object.first_name }}
{{ object.last_name }}

In the django shell i'm trying following:

>>> from haystack.query import SearchQuerySet

>>> sqs=SearchQuerySet()
>>> sqs
[<SearchResult: tooldb.applicant (pk=u'1')>, <SearchResult: tooldb.applicant (pk=u'2')>]

>>> sqs[0].gender
u'M'     #<-- So this seems to be indexed

#but when i try:
>>> sqs.filter(gender='M')
[]     #<-- I get nothing ... ?

I tried it with other CharFields without choices and max_lenght > 1, no problem at all, haystack filters like it should.

What am I missing?


Solution

  • Here is my solution:

    class ApplicantIndex(indexes.SearchIndex, indexes.Indexable):
        text = indexes.CharField(document=True, use_template=True)
        gender = indexes.CharField()
    
        def prepare_gender(self, obj):
            return obj.gender*3
    

    Now you can filter like:

    sqs.filter(gender='MMM')