Django Haystack索引来自同一模型的多个字段 [英] Django Haystack index on multiple fields from same model
问题描述
我正在尝试使用 django-haystack
将elasticsearch嵌入我的Django应用程序中。我正在尝试实施用户搜索。我的用户模型是这样的:
I am trying to embed elasticsearch in my Django app using django-haystack
. I am trying to implement a user search. My user model is this:
class MyUser(AbstractBaseUser):
username = models.CharField(max_length=255, unique=True)
name = models.CharField(max_length=63, blank=True)
email = models.EmailField(blank=True, unique=True)
status = models.CharField(max_length=255, blank=True, null=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
joined = models.DateTimeField(auto_now_add=True, null=True)
现在,我要搜索名称
和用户名
字段。我创建了以下 search_indexes.py
:
Now, I want to search on name
and username
fields. I have created the following search_indexes.py
:
class UserIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, model_attr='name')
username = indexes.CharField(model_attr='username')
def get_model(self):
return MyUser
def get_updated_field(self):
return "joined"
但是,当我执行搜索时,只会得到与 name
字段匹配的结果。我在这里做错了什么?还有其他方法吗?
However, when I perform a search, I only get the results matching the name
field. What am I doing wrong here? Is there some other way to do this?
预先感谢。
推荐答案
django-haystack的工作方式, document = True
字段中的数据用于常规搜索,而其他字段则用于单个过滤。因此,在您的情况下,搜索将仅使用 name
字段。要解决此问题,您需要使用一个模板,该模板指定搜索中要使用的所有字段。首先,使用:
The way django-haystack works, the data inside the document=True
field is used for a general search, and any other fields are used for individual filtering. So in your case, a search will only use the name
field. To fix this, you'll need to use a template that specifies all the fields to be used in a search. First of all, use:
text = indexes.EdgeNgramField(document=True, use_template=True)
然后,您需要在模板目录中创建一个名为 search / indexes / myapp /的新模板myuser_text.txt
并将以下内容放入其中:
Then you’ll need to create a new template inside your template directory called search/indexes/myapp/myuser_text.txt
and place the following inside:
{{ object.username }}
{{ object.name }}
请参见 http://django-haystack.readthedocs.org/en/latest/tutorial.html#handling-data 供参考
这篇关于Django Haystack索引来自同一模型的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!