Django

Setup

Install

pip install algoliasearch-django

Setup

In your Django settings, add django.contrib.algoliasearch to INSTALLED_APPS and add these two settings:

ALGOLIA = {
    'APPLICATION_ID': 'MyAppID',
    'API_KEY': 'MyApiKey'
}

There are two optional settings:

  • INDEX_PREFIX: prefix all indexes. Use it to separate different applications, like site1_Products and site2_Products.
  • INDEX_SUFFIX: suffix all indexes. Use it to differenciate development and production environment, like Location_dev and Location_prod.
  • AUTO_INDEXING: automatically synchronize the models with Algolia (default to True).

Quick Start

Simply call AlgoliaSearch.register() for each of the models you want to index. A good place to do this is in your application’s AppConfig (generally named apps.py). More info in the documentation

from django.apps import AppConfig
from django.contrib import algoliasearch

class YourAppConfig(AppConfig):
    name = 'your_app'

    def ready(self):
        YourModel = self.get_model('your_model')
        algoliasearch.register(YourModel)

And then, don’t forget the line below in the __init__.py file of your Django application.

default_app_config = 'your_django_app.apps.YourAppConfig'

By default, all the fields of your model will be used. You can configure the index by creating a subclass of AlgoliaIndex. A good place to do this is in a separate file, like index.py.

from django.contrib.algoliasearch import AlgoliaIndex

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

And then replace algoliasearch.register(YourModel) with algoliasearch.register(YourModel, YourModelIndex).

Did you find this page helpful?

We're always looking for advice to help improve our documentation! Please let us know what's working (or what's not!) - we're constantly iterating thanks to the feedback we receive.

Send us your suggestions!