algolia / algoliasearch-django

Seamless integration of Algolia into your Django project.
https://www.algolia.com
MIT License
173 stars 65 forks source link

Dynamic way to use multiple indexes per models #252

Open clemfromspace opened 6 years ago

clemfromspace commented 6 years ago

Hello there :)

Recently, I found myself in the needs to add multiple indexes per models, but in a dynamic way.

I used django-hvad for the model translations, and needed to "route" the models to a different index based on the language_code field of the model.

Do you know how if there is a way I could achieve this ?

julienbourdeau commented 6 years ago

I don't think it's possible today but it's definitely something that we should handle.

I'm thinking we could have a new method get_index_name and move this logic into it: https://github.com/algolia/algoliasearch-django/blob/master/algoliasearch_django/models.py#L164-L171 then everyone would be able to override it. What do you think?

PLNech commented 6 years ago

I would use the same convention as for tags: if it's a member just take it, if it's a callable call it everytime we need its value. This way we don't introduce a new get_xxx method, we just replace the xxx field by a callable :)

clemfromspace commented 6 years ago

The tags solution looks good to me, if I understand correctly and if it gets implemented I should be able to do the following for a django model:

class MyTranslatableModel(models.Model):
    language_code = models.CharField(max_length=2)

    @property  # Or any callable / attribute
    def index_name(self):
        return 'index_name_{}'.format(self.language_code)

If that's the case, it will be perfect!

I will gladly help implementing this :)