Haystack - how do you display data from multiple models using ForeignKeys?

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 filed1_model1, but when I do this, I want to also show filed2_model2 in the search results.

What happens in the search_indexes.py file as well as in the search.html template files for this to happen?

+7
source share
1 answer

You must first add the associated name to your foreign key so that you can call it later.

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

Then the Model1 index. For field2_model2, prepare the data by receiving the information as shown 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 will display data using {{ result.field1_model1 }} and {{ result.field2_model2 }}

Remember to add fields to your .txt file, possibly called model1_text.txt in templates β†’ search β†’ indexes β†’ app_name. (or something similar)

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

And then you just need to update the chart and rebuild your index, and you should be good to go.

+6
source

All Articles