Question

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?

Was it helpful?

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')

OTHER TIPS

Okay i think i got it..

It seems like haystack in combination with whoosh doesn't work with single char queries at all.
This is kind of annoying cause SearchQuerySet should be implemented in the way Django's QuerySet works. (https://django-haystack.readthedocs.org/en/v2.1.0/searchqueryset_api.html#why-follow-queryset)

QuerySet's filter method works fine with one character as query, SearchQuerySet just returns nothing.

This should be documented somewhere...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top