我有博客帖子,我试图在搜索索引中添加评论,但由于某些原因无法工作……我的评论有通用的外键,如果重要的话。顺便说一句,它适用于标签。
class BlogIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
headline = indexes.CharField(model_attr="headline", null=True)
body = indexes.CharField(model_attr="body")
date = indexes.DateTimeField(model_attr='date')
mytags = indexes.MultiValueField()
mycomments = indexes.MultiValueField()
def prepare_mytags(self, obj):
return [tag.name for tag in obj.tags.all()]
def prepare_mycomments(self, obj):
cur_model = ContentType.objects.get_for_model(obj)
cur_comments = Comment.objects.filter(content_type=cur_model, object_pk=obj.id)
return [str(cur_c.content) for cur_c in cur_comments]
def get_model(self):
return Snip
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(date__lte=timezone.now())这是我的模板:
{{ object.headline }}
{{ object.body }}
{% for c in object.mycomments %}{{ c }} {% endfor %}
{% for tag in object.tags.all %}{{ tag.name }} {% endfor %}如果重要的话,我还使用了drf-haystack,这是序列化程序:
class BlogSearchSerializer(HaystackSerializer):
class Meta:
index_classes = [BlogIndex]
fields = [
"headline", "body", "date", "mytags", 'mycomments', "content",
]当我用content=XX搜索时,它在评论中找不到任何东西。
我做错了什么?
谢谢R
发布于 2016-07-20 17:25:14
您的模板是错误的-具体而言,您正在执行以下操作:
{% for c in object.mycomments %}{{ c }} {% endfor %}本例中的object是Blog的实例,而不是BlogIndex的实例。模板引擎将找不到任何类似的东西,也不会做任何事情。您可能希望这样做:
{% for c in object.comment_set.all %}{{ c }}{% endfor %}假设您的注释有一个指向它们所附加的Blog项的外键。
你实际上不需要在BlogIndex.mycomments中单独索引它们,除非你想做更多的事情而不仅仅是搜索(例如,过滤/分面)。
https://stackoverflow.com/questions/38477017
复制相似问题