Indexing Multi-value fields from django-tagging in Haystack

Enabling tagging on models is easy when you use django-tagging. However, I also have a search feature which is powered by Haystack and Whoosh. I wanted to be able to search for objects by the tags that are associated with them. You need to use the following in your haystack SearchIndex model:

tags = indexes.MultiValueField(indexed=True, stored=True)

Full Example

myproject/myapp/models.py

from django.db import models,
from tagging.fields import TagField
class Template(models.Model):
        name = models.CharField(max_length=100)
        pub_date = models.DateTimeField(editable=False, blank=True)
        description = models.TextField(blank=True)
        slug = models.SlugField(unique=True,editable=False,blank=True,null=True)
        tags = TagField()

myproject/myapp/search_indexes.py

import datetime
from haystack import indexes
from generator.models import Template


class TemplateIndex(indexes.RealTimeSearchIndex):
    text = indexes.CharField(document=True, use_template=True)
    name = indexes.CharField(model_attr='name')
    description = indexes.CharField(model_attr='description')
    pub_date = indexes.DateTimeField(model_attr='pub_date')
    tags = indexes.MultiValueField(indexed=True, stored=True)


    def get_model(self):
        return Template

    def index_queryset(self):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.filter(pub_date__lte=datetime.datetime.now())

Tagged as django , haystack
Written by Andrew Konkol on July 22nd, 2011

3 Comments

what do you do to display those tags in the template? Are you using a {% for a in result.object.tags %}{{ a.tag}} {% endfor %} iteration ? I have a similar thing on my project and I got stuck.

geo
July 29, 2011
geo: a section of my /templates/search/search.html looks like this: {% for result in page.object_list %} {{result.object.name}} {{result.object.description|truncatewords:30}} tags: {{result.object.tags}} {% empty %} No results found. {% endfor %}

Andrew Konkol
July 30, 2011
Do you include the tags in your index template as well?

stephen.paulger
November 28, 2012
Log in with Twitter, Google, Facebook, LinkedIn to leave a comment.