Skip to content

Preserve field names after preprocessing a field #322

@ademidun

Description

@ademidun

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

Similar issue: #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()]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions