Integrations / Frameworks / Django / Setting Up Algolia for Django

Setting Up Algolia for Django

Introduction# A

This package lets you easily integrate the Algolia Search API into your Django project. It’s based on the algoliasearch-client-python package.

You might be interested in this sample Django application providing a typeahead.js based autocompletion and Google-like instant search: algoliasearch-django-example.

  • Compatible with Python 2.7 and Python 3.4+.
  • Supports Django 1.7+, 2.x and 3.x.

Install# A

1
pip install --upgrade 'algoliasearch-django>=2.0,<3.0'

Setup# A

In your Django settings, add algoliasearch_django to INSTALLED_APPS and add these two settings:

1
2
3
4
ALGOLIA = {
    'APPLICATION_ID': 'AJ0P3S7DWQ',
    'API_KEY': '••••••••••••••••••••'
}

There are several optional settings:

  • INDEX_PREFIX: prefix all indices. Use it to separate different applications, like site1_Products and site2_Products.
  • INDEX_SUFFIX: suffix all indices. Use it to differentiate development and production environments, like Location_dev and Location_prod.
  • AUTO_INDEXING: automatically synchronize the models with Algolia (default to True).
  • RAISE_EXCEPTIONS: raise exceptions on network errors instead of logging them (default to settings.DEBUG).

Quick Start# A

Create an index.py inside each application that contains the models you want to index. Inside this file, call algoliasearch.register() for each of the models you want to index:

1
2
3
4
5
6
7
# index.py

import algoliasearch_django as algoliasearch

from .models import YourModel

algoliasearch.register(YourModel)

By default, all the fields of your model will be used. You can configure the index by creating a subclass of AlgoliaIndex and using the register decorator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# index.py

from algoliasearch_django import AlgoliaIndex
from algoliasearch_django.decorators import register

from .models import YourModel

@register(YourModel)
class YourModelIndex(AlgoliaIndex):
    fields = ('name', 'date')
    geo_field = 'location'
    settings = {'searchableAttributes': ['name']}
    index_name = 'my_index'

Did you find this page helpful?