Search code examples
pythondjangodjango-haystack

Search over multiple fields


I think I don't unterstand django-haystack properly:

I have a data model containing several fields, and I would to have two of them searched:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True, default=None)
    twitter_account = models.CharField(max_length=50, blank=False)

My search index settings:

class UserProfileIndex(SearchIndex):
    text = CharField(document=True, model_attr='user')
    twitter_account = CharField(model_attr='twitter_account')

    def get_queryset(self):
        """Used when the entire index for model is updated."""
        return UserProfile.objects.all()

But when I perform a search, only the field "username" is searched; "twitter_account" is ignored. When I select the Searchresults via dbshell, the objects contain the correct values for "user" and "twitter_account", but the result page shows a "no results":

    {% if query %}
        <h3>Results</h3>

        {% for result in page.object_list %}
            <p>
               <a href="{{ result.object.get_absolute_url }}">{{ result.object.id }}</a>
            </p>
        {% empty %}
            <p>No results</p>
        {% endfor %}
    {% endif %}

Any ideas?


Solution

  • I guess thats because haystack uses the document field for generic searches unless you define a specific search for other fields like the twitter_account field.

    from haystack documentation

    Every SearchIndex requires there be one (and only one) field with document=True. This indicates to both Haystack and the search engine about which field is the primary field for searching within.

    Try specifing the index as follows

    class UserProfileIndex(SearchIndex):
        text = CharField(document=True, use_template=True)
        user = CharField(model_attr='user')
        twitter_account = CharField(model_attr='twitter_account')
    

    and create the a file named search/indexes//userprofile_text.txt

    which will contain the following

    {{ object.user.get_full_name }}
    {{ object.twitter_account}}
    

    now haystack will search in the contents of this file (where you can add whatever you want) when you don't specify an index filter.