Search code examples
djangoalgoliadjango-taggit

Indexing Taggit tags with Algolia for Django: '_TaggableManager' object has no attribute 'name'


I'm having some issues using the Algolia Django integration with one of my models which contains a TaggitManager() field. I'm currently being thrown back the following error when running this command:

$ python manage.py algolia_reindex

AttributeError: '_TaggableManager' object has no attribute 'name'

I've had a look at the Taggit documentation, but I'm just not sure exactly how I would marry the method outlined with the Algolia search index method.

index.py:

import django
django.setup()

from algoliasearch_django import AlgoliaIndex

class BlogPostIndex(AlgoliaIndex):
    fields = ('title')
    settings = {'searchableAttributes': ['title']}
    index_name = 'blog_post_index'

models.py:

from taggit.managers import TaggableManager

class Post(models.Model):
    ...some model fields...

    tags = TaggableManager()

Solution

  • To index the taggit tags with your Post fields, you will need to expose a callable that returns a Blog Post's tags as a list of strings.

    The best option is to store them as _tags, which will let you filter on tags at query time.

    Your PostIndex would look like this:

    class PostIndex(AlgoliaIndex):
        fields = ('title', '_tags')
        settings = {'searchableAttributes': ['title']}
        index_name = 'Blog Posts Index'
        should_index = 'is_published'
    

    As for Post:

    class Post(models.Model):
        # ...some model fields...
    
        tags = TaggableManager()
    
        def _tags(self):
            return [t.name for t in self.tags.all()]
    

    Following these instructions, your records will be indexed with their respective tags:

    Screenshot of a tagAlgolia explorer

    You can check the taggit branch of our Django demo, which demonstrates these steps.