我正在与Django-Haystack苦苦挣扎。Django-Haystack - 如何使用Haystack与Django的评论?
我需要做一个包含文章和评论文章的索引。我的疑问是,我怎样才能在基于文件的索引文章和评论。
如何在评论和文章中搜索关键词并使用该关键词输出文章(文章评论,文章)?
有可能吗?
最好的问候,
我正在与Django-Haystack苦苦挣扎。Django-Haystack - 如何使用Haystack与Django的评论?
我需要做一个包含文章和评论文章的索引。我的疑问是,我怎样才能在基于文件的索引文章和评论。
如何在评论和文章中搜索关键词并使用该关键词输出文章(文章评论,文章)?
有可能吗?
最好的问候,
做的第一件事是忘记一个SearchIndex
必须完全符合模型的概念。它只来自一个。
最简单的方法是使用模板将注释添加到索引文档。这个假定你的Article
模型作为title
场:
class ArticleIndex(SearchIndex, indexes.Indexable):
text = CharField(document=True, use_template=True)
title = CharField(model_attr='title')
def get_model(self):
return Article
注意关键字参数use_template
设置为true。这个的默认值是search/indexes/{app_label}/{model_name}_{field_name}.txt。在该模板中输出您想要索引的内容。例如。
{{ object.title|safe }}
{{ object.body|safe }}
{% for comment in object.comments.all %}
{{ comment|safe }}
{% endfor %}
虽然恐怕这里的具体反向关系名称可能是错误的,那就是你想要做的事情的要点。再次,这是完成你特别说明的一个简单的方法。
这是对我工作:
在你models.py
,假定注释附加到Article
,你想返回连接到它的意见的方法(有没有简单的方法来做到这一点):
class Article:
def comments(self):
ids = [self.id]
ctype = ContentType.objects.get_for_model(Article)
comments = Comment.objects.filter(content_type=ctype,
object_pk__in=ids,
is_removed=False)
return comments
在你search_indexes.py
,确保ArticleIndex
有use_template=True
:
from django.contrib.contenttypes.models import ContentType
from django.contrib.comments.models import Comment
class ArticleIndex(SearchIndex):
text = CharField(use_template=True)
在您的索引模板中,例如templates/search/indexes/article_text.txt:
{% for comment in object.comments.all %}
{{ comment }}
{% endfor %}
现在,唯一剩下的问题是,当一个注释添加或移除来更新该特定索引对象。这里我们使用的信号:
在你的models.py:
from django.dispatch import receiver
from haystack import site
from django.contrib.comments.signals import (comment_was_posted,
comment_was_flagged)
@receiver(comment_was_posted)
def comment_posted(sender, **kwargs):
site.get_index(Article).update_object(kwargs['comment'].content_object)
@receiver(comment_was_flagged)
def comment_flagged(sender, **kwargs):
site.get_index(Article).update_object(kwargs['comment'].content_object)
这显然不再适用。在当前版本的haystack中,>>> from haystack import site Traceback:ImportError:无法导入名称'site' – shacker 2016-01-19 21:56:05