Integrations / Frameworks / Django / Options

Custom objectID

You can choose which field will be used as the objectID. The field should be unique and can be a string or integer. By default, we use the pk field of the model.

1
2
class ArticleIndex(AlgoliaIndex):
    custom_objectID = 'post_id'

</section>

Custom index name

You can customize the index name. By default, the index name will be the name of the model class.

1
2
class ContactIndex(algoliaindex):
    index_name = 'Enterprise'

If you want to process a field before indexing it (e.g. capitalizing a Contact’s name), or if you want to index a related object’s attribute, you need to define proxy methods for these fields.

Models

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Account(models.Model):
    username = models.CharField(max_length=40)
    service = models.CharField(max_length=40)

class Contact(models.Model):
    name = models.CharField(max_length=40)
    email = models.EmailField(max_length=60)
    //...
    accounts = models.ManyToManyField(Account)

    def account_names(self):
        return [str(account) for account in self.accounts.all()]

    def account_ids(self):
        return [account.id for account in self.accounts.all()]

Index

1
2
3
4
5
6
7
8
9
10
from algoliasearch_django import AlgoliaIndex


class ContactIndex(AlgoliaIndex):
    fields = ('name', 'email', 'company', 'address', 'city', 'county',
              'state', 'zip_code', 'phone', 'fax', 'web', 'followers', 'account_names', 'account_ids')

    settings = {
        'searchableAttributes': ['name', 'email', 'company', 'city', 'county', 'account_names',
        }
  • With this configuration, you can search for a Contact using its Account names
  • You can use the associated account_ids at search-time to fetch more data from your model (you should only proxy the fields relevant for search to keep your records’ size as small as possible)

Index settings

We provide many ways to configure your index allowing you to tune your overall index relevancy. All the configuration is explained on our doc.

1
2
3
4
5
class ArticleIndex(AlgoliaIndex):
    settings = {
        'searchableAttributes': ['name', 'description', 'url'],
        'customRanking': ['desc(vote_count)', 'asc(name)']
    }

Restrict indexing to a subset of your data

You can add constraints controlling if a record must be indexed or not. should_index should be a callable that returns a boolean.

1
2
3
4
5
6
7
8
9
class Contact(models.model):
    name = models.CharField(max_length=20)
    age = models.IntegerField()

    def is_adult(self):
        return (self.age >= 18)

class ContactIndex(AlgoliaIndex):
    should_index = 'is_adult'

Multiple indices per model

It is possible to have several indices for a single model.

  • First, define all your indices that you want for a model:
1
2
3
4
5
6
7
8
9
from django.contrib.algoliasearch import AlgoliaIndex

class MyModelIndex1(AlgoliaIndex):
    name = 'MyModelIndex1'
    ...

class MyModelIndex2(AlgoliaIndex):
    name = 'MyModelIndex2'
    ...
  • Then, define a meta model which will aggregate those indices:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class MyModelMetaIndex(AlgoliaIndex):
    def __init__(self, model, client, settings):
        self.indices = [
            MyModelIndex1(model, client, settings),
            MyModelIndex2(model, client, settings),
        ]

    def raw_search(self, query='', params=None):
        res = {}
        for index in self.indices:
            res[index.name] = index.raw_search(query, params)
        return res

    def update_records(self, qs, batch_size=1000, **kwargs):
        for index in self.indices:
            index.update_records(qs, batch_size, **kwargs)

    def reindex_all(self, batch_size=1000):
        for index in self.indices:
            index.reindex_all(batch_size)

    def set_settings(self):
        for index in self.indices:
            index.set_settings()

    def clear_index(self):
        for index in self.indices:
            index.clear_index()

    def save_record(self, instance, update_fields=None, **kwargs):
        for index in self.indices:
            index.save_record(instance, update_fields, **kwargs)

    def delete_record(self, instance):
        for index in self.indices:
            index.delete_record(instance)
  • Finally, register this AlgoliaIndex with your Model:
1
2
import algoliasearch_django as algoliasearch
algoliasearch.register(MyModel, MyModelMetaIndex)

Temporarily disable the auto-indexing

It is possible to temporarily disable the auto-indexing feature using the disable_auto_indexing context decorator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from algoliasearch_django.decorators import disable_auto_indexing

# Used as a context manager
with disable_auto_indexing():
    MyModel.save()

# Used as a decorator
@disable_auto_indexing():
my_method()

# You can also specifiy for which model you want to disable the auto-indexing
with disable_auto_indexing(MyModel):
    MyModel.save()
    MyOtherModel.save()

Did you find this page helpful?