newbie
newbie

Reputation: 24645

Django Haystack custom form custom attribute returns no results

I have made my own SearchForm following instructions from Django website, but for some reason if I add my own search field, it doesn't return any results, even when it should return results.

My search_indexes.py:

from haystack import indexes 
from my.app.models import MyModel

class MyIndexIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.NgramField(document=True, use_template=True)    
    my_fieldname = indexes.CharField(model_attr='my_fieldname')

    def get_model(self):
        return MyModel

My model:

class MyModel(models.Model):
    some_field1 = models.CharField(_('Some field 1'), max_length=255)
    some_field2 = models.CharField(_('Some field 2'), max_length=255)

    my_fieldname = models.CharField(_('My field name'), max_length=255)

My search form:

class MySearchForm(SearchForm):
    q = forms.CharField(label="Search", max_length=255, required=False)
    my_fieldname = forms.CharField(label="MySearchLabel", max_length=255, required=False)

    def search(self):
        sqs = super(MySearchForm, self).search()

        if self.is_valid() and self.cleaned_data['my_fieldname']:
            sqs = sqs.filter(my_fieldname=AutoQuery(self.cleaned_data['my_fieldname']))

        return sqs

My urls.py:

urlpatterns += patterns('haystack.views',
    url(r'^search/', SearchView(
        form_class=MySearchForm
    ), name='haystack_search'),
)

I have run manage.py rebuild_index, but it doesn't affect. My question is what I am doing wrong here, why I am not getting any results. If I try some queries with q parameters, results are returned normally.

Upvotes: 0

Views: 614

Answers (1)

Bernhard Vallant
Bernhard Vallant

Reputation: 50796

super(MySearchForm, self).search() performs an auto_query() with a default field name of content... As you haven't defined a field like this it will not return any results... Therefore I wouldn't do the super call, but replace with an implementation similar to the original one - but pass a fieldname to auto_query: auto_query(querystring, fieldname='text').

Also make sure to have the template defined correctly if you are searching in it. (If you are chaining multiple filter() calls they will be combined usind and).

Also depending on the search engine you use it will probably offer you a frontend where you can check independently from haystack if the data is indexed properly...

Upvotes: 1

Related Questions