8

I have two models:

models.py

class model1 (models.Model):
   field1_model1 = models.CharField()
   filed2_model1 = models.CharField()

class model2 (models.Model):
   field1_model2 = models.ForeignKey(model1)
   field2_model2 = models.CharField()

Using Haystack I want to do a text search based on the filed1_model1 but when I do that I want to show also filed2_model2 in the search results.

What goes in the search_indexes.py and also in the search.html template files to make this happen?

Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
avatar
  • 12,087
  • 17
  • 66
  • 82

1 Answers1

7

First you should add a related name to your foreign key so you can call it later.

class Model2(models.Model):
   field1_model2 = models.ForeignKey(Model1, related_name='something')
   field2_model2 = models.CharField()

Then index Model1. For field2_model2, prepare the data by getting the info as seen below.

class Model1Index(indexes.SearchIndex):
    text = indexes.CharField(document=True, use_template=True)
    field1_model1 = indexes.CharField(model_attr='field1_model1', faceted=True)
    field2_model2 = indexes.Charfield()

    def prepare_field2_model2(self, obj):
        return obj.something.field2_model2

site.register(Model1, Model1Index)

In your search.html you would display the data with {{ result.field1_model1 }} and {{ result.field2_model2 }}

Don't forget to add the fields to your .txt file, probably called model1_text.txt in templates -> search -> indexes -> app_name. (or something similar)

{{ object.field1_model1 }}
{{ object.field2_model2 }}

And then it should just be a matter of updating the schema and rebuilding your index and you should be good to go.

TomHarrigan
  • 618
  • 4
  • 10
  • 1
    This got me on the right track. I think the method name should be prepare_field2_model2 instead of prepare_name. Here's the related haystack docs: http://docs.haystacksearch.org/dev/searchindex_api.html#prepare-foo-self-object – Jeff Oct 11 '11 at 01:04
  • Sounds right. Glad it helped. I'll update the answer w/ your correction. – TomHarrigan Oct 11 '11 at 20:14