algoliasearch-django icon indicating copy to clipboard operation
algoliasearch-django copied to clipboard

Preserve field names after preprocessing a field

Open ademidun opened this issue 3 years ago • 0 comments

The Algolia Field Preprocessing example says that we can define a custom method if we want to preproces a field.

Similar issue: https://github.com/algolia/algoliasearch-django/issues/2

This allows the ManyToMany field accounts to be saved as a JSON serializable searchable attribute in our Algolia index as account_names.

Is there a way to transform accounts so that it is transformed to have the same value as account_names while keeping the original name.

The use case is that my Django server exposes a REST API using the Django Rest Framework which also serializes the ManyToManyField and is consumed by my frontend client which uses the original name (e.g. accounts). I don't want to maintain 2 sets of field names.

I'm envisioning something like a field_mappings attribute:

from algoliasearch_django import AlgoliaIndex


class ContactIndex(AlgoliaIndex):
    fields = ('name', 'email', 'account_names', 'account_ids')

    settings = {
        'searchableAttributes': ['name', 'email', 'account_names']
        }
    field_mappings = { 'account_names': 'accounts'} #<--- This is the new line



# models.py
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()]

ademidun avatar Jan 20 '22 13:01 ademidun