【问题标题】:Haystack - Can't find object with prepared fieldsHaystack - 找不到具有准备好的字段的对象
【发布时间】:2016-11-23 10:33:15
【问题描述】:

我有博客文章,我正在尝试将 cmets 添加到搜索索引,但由于某种原因它不起作用... 如果重要,我的 cmets 具有通用外键。 顺便说一句,它适用于标签。

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 进行搜索时,它在 cmets 中找不到任何内容。

我做错了什么?

谢谢 回复

【问题讨论】:

    标签: django indexing full-text-search django-rest-framework django-haystack


    【解决方案1】:

    你的模板是错误的——特别是你这样做:

    {% for c in object.mycomments %}{{ c }} {% endfor %}
    

    object 在这种情况下是Blog 的实例,而不是BlogIndex 的实例。模板引擎将无法找到类似的东西,并且不会做任何事情。您可能想要这样做:

    {% for c in object.comment_set.all %}{{ c }}{% endfor %}
    

    假设您的 cmets 具有指向它们所附加到的 Blog 项目的外键。

    您实际上不需要在 BlogIndex.mycomments 中单独索引它们,除非您想做的不仅仅是搜索它们(例如,过滤/分面)。

    【讨论】:

    • 问题是评论的外键是通用外键,因此我不能使用comment_set AFAK。谢谢!
    • 我修复了它,但不是完全修复。我将comments = GenericRelation(Comment) 添加到我的博客模型中,现在我可以使用 /?content=XX 对其进行索引和搜索,但我不能只在 cmets 中搜索,也无法使用 drf-haystack 在结果中显示 cmets。
    • 您可以向您的Blog 模型添加一个方法,例如get_comments,它执行您当前在BlogIndex.prepare_mycomments 中的逻辑并返回一组cmets。然后您可以使用object.get_comments 在模板中访问它。
    • 我通过使用这个来修复它:def load_all_queryset(self): return Blog.objects.all().select_related() 但是我如何使用 drf-haystack 在结果中显示 cmets(标签也丢失了)?意思是,搜索正常,但显示不正确。
    • 不确定 - 对 DRF 不够熟悉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多