Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve field names after preprocessing a field #322

Open
ademidun opened this issue Jan 20, 2022 · 0 comments
Open

Preserve field names after preprocessing a field #322

ademidun opened this issue Jan 20, 2022 · 0 comments

Comments

@ademidun
Copy link

ademidun commented Jan 20, 2022

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()]
ademidun added a commit to ademidun/atila-client-web-app that referenced this issue Jan 20, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant