Search code examples
djangosearchsphinxsphinxqldjango-sphinx

How to use two models for single index search in sphinx-django


I'm using django-sphinxql for search requirements in my django project. I want to use two models in my app for search with some query. Models look as below

Class Model1(models.Model):
    name = models.CharField(max_length=50)
    model2 = models.ForeignKey(Model2, on_delete=models.CASCADE)

Class Model2(models.Model):
    caption = models.CharField(max_length=50)

I want to enable search for both name and caption fields above such that Model1 is returned for any matches, e.g. if query="abc" matches caption the response should be Model1, How would I achieve that I've created index for Model1 but don't know how to add caption from Model2 in it as well. My index for Model1 is as below

class Model1Index(indexes.Index):
    name = fields.Text(model_attr='name')
    class Meta:
        model = Model1
        settings.INDEXES['source_params'] = {'sql_field_string': ['name'],}

Quick help is appreciate.


Solution

  • For foreign key fields in Sphinx we can use double underscores(__) to point to specific field for indexing. User model_attr for this

    In above example

    class Model1Index(indexes.Index): name = fields.Text(model_attr='name') caption = fields.Text(model_attr='model2__caption') class Meta: model = Model1 settings.INDEXES['source_params'] = {'sql_field_string': ['name'],}

    can be defined.

    Reference http://django-sphinxql.readthedocs.io/en/latest/indexes.html