haystack - 如何使用外键显示来自多个模型的数据? [英] haystack - how you display data from multiple models with ForeignKeys?

查看:35
本文介绍了haystack - 如何使用外键显示来自多个模型的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型:

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()

我想使用 Haystack 进行基于filed1_model1 的文本搜索,但是当我这样做时,我还想在搜索结果中显示filed2_model2.

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.

search_indexes.py 和 search.html 模板文件中的哪些内容可以实现这一点?

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

推荐答案

首先你应该为你的外键添加一个相关的名称,以便你以后可以调用它.

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()

然后索引 Model1.对于 field2_model2,通过获取信息来准备数据,如下所示.

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)

在您的 search.html 中,您将使用 {{ result.field1_model1 }}{{ result.field2_model2 }}

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

不要忘记将字段添加到您的 .txt 文件中,可能在模板 -> 搜索 -> 索引 -> app_name 中称为 model1_text.txt.(或类似的东西)

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.

这篇关于haystack - 如何使用外键显示来自多个模型的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆