haystack - how you display data from multiple models with ForeignKeys?

我的未来我决定 提交于 2019-11-30 09:32:13

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!