我有一个段落模型的两个字段,其中一个是ManyToMany字段。
class Tag(models.Model):
tag = models.CharField(max_length=500)
def __unicode__(self):
return self.tag
admin.site.register(Tag)
class Paragraph(models.Model):
article = models.ForeignKey(Article)
text = models.TextField()
tags = models.ManyToManyField(Tag)
def __unicode__(self):
return "Headline: " + self.article.headline + " Tags: " + ', '.join([t.tag for t in self.tags.all()])
admin.site.register(Paragraph)
我的.txt文件反映了与索引标签的ManyToMany关系 -
{{object.text}}
{% for tag in object.tags.all %}
{{tag.tag}}
{% endfor %}
我的views.py然后使用SQS搜索所有标记(我想在包含文本字段之前先完成此操作)并检索它们。所以在这种情况下,查询是“政治” -
def politics(request):
paragraphs = []
sqs = SearchQuerySet().filter(tag="Politics")
paragraphs = [a.object for a in sqs[0:10]]
return render_to_response("search/home_politics.html",{"paragraphs":paragraphs},context_instance=RequestContext(request))
编辑: 和我的search_indexes.py
class ParagraphIndex(indexes.SearchIndex, indexes.Indexable):
text= indexes.CharField(document=True, use_template=True)
tags= indexes.CharField(model_attr='tags')
def get_model(self):
return Paragraph
def index_queryset(self):
return self.get_model().objects
def load_all_queryset(self):
# Pull all objects related to the Paragraph in search results.
return Paragraph.objects.all().select_related()
然而,即使一些段落的标签是“政治”,这也不会反复。我在这里遗漏了什么或者我应该以另一种方式处理相关数据吗?我是Haystack的初学者,所以任何帮助都会非常感激。提前致谢!
答案 0 :(得分:3)
所以这是一个非常useful article帮助我解决问题。
根据这篇文章,这就是我的search_indexes.py现在的样子:
class ParagraphIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
tags = indexes.MultiValueField()
def prepare_tags(self,object):
return [tag.tag for tag in object.tags.all()]
def get_model(self):
return Paragraph
def index_queryset(self):
return self.get_model().objects
def load_all_queryset(self):
# Pull all objects related to Paragraph in search results.
return Paragraph.objects.all().select_related()
和我的views.py:
def politics(request):
paragraphs = []
sqs = SearchQuerySet().filter(tags='Politics')
paragraphs = [a.object for a in sqs[0:10]]
return render_to_response("search/home.html",
{"paragraphs":paragraphs},
context_instance=RequestContext(request))
我正在使用弹性搜索引擎。希望这有帮助!