搜索多个字段 [英] Search over multiple fields
问题描述
我认为我并没有正确理解django-haystack:
I think I don't unterstand django-haystack properly:
我有一个包含多个字段的数据模型,我需要搜索其中两个字段:
I have a data model containing several fields, and I would to have two of them searched:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True, default=None)
twitter_account = models.CharField(max_length=50, blank=False)
我的搜索索引设置:
class UserProfileIndex(SearchIndex):
text = CharField(document=True, model_attr='user')
twitter_account = CharField(model_attr='twitter_account')
def get_queryset(self):
"""Used when the entire index for model is updated."""
return UserProfile.objects.all()
但是当我执行搜索时,只有字段搜索用户名; twitter_account将被忽略。当我通过dbshell选择Searchresults时,对象包含 user和 twitter_account的正确值,但结果页面显示无结果:
But when I perform a search, only the field "username" is searched; "twitter_account" is ignored. When I select the Searchresults via dbshell, the objects contain the correct values for "user" and "twitter_account", but the result page shows a "no results":
{% if query %}
<h3>Results</h3>
{% for result in page.object_list %}
<p>
<a href="{{ result.object.get_absolute_url }}">{{ result.object.id }}</a>
</p>
{% empty %}
<p>No results</p>
{% endfor %}
{% endif %}
有什么想法吗?
推荐答案
我猜想那是因为haystack使用document字段进行常规搜索,除非您为twitter_account字段等其他字段定义了特定的搜索。
I guess thats because haystack uses the document field for generic searches unless you define a specific search for other fields like the twitter_account field.
每个SearchIndex都需要
一个(也只有一个)包含$ b的字段$ b document = True。这向
Haystack和搜索引擎都指示了大约
,该字段是
在其中进行搜索的主要字段。
Every SearchIndex requires there be one (and only one) field with document=True. This indicates to both Haystack and the search engine about which field is the primary field for searching within.
尝试按如下方式指定索引
Try specifing the index as follows
class UserProfileIndex(SearchIndex):
text = CharField(document=True, use_template=True)
user = CharField(model_attr='user')
twitter_account = CharField(model_attr='twitter_account')
并创建一个名为
search / indexes // userprofile_text.txt的文件
and create the a file named search/indexes//userprofile_text.txt
以下
{{ object.user.get_full_name }}
{{ object.twitter_account}}
现在,当您不指定干草堆时,干草堆将搜索该文件的内容(您可以在其中添加所需内容)索引过滤器。
now haystack will search in the contents of this file (where you can add whatever you want) when you don't specify an index filter.
这篇关于搜索多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!