python - 使用 Django haystack MultiValueField 迭代搜索结果 View 中的项目

标签 python django search django-haystack

如果我的一个搜索索引上有一个 MultiValueField,并且我想在搜索结果中显示每个值,我该怎么做?似乎某些内容的格式不正确,或者我以某种方式误解了 MultiValueField?

class PageAttachmentIndex(indexes.SearchIndex):
    # This should reference search/indexes/pages/pageattachment_text.txt
    text      = indexes.CharField(document=True, use_template=True)
    title     = indexes.CharField(model_attr='name')
    page      = indexes.IntegerField(model_attr='page_id')
    attrs     = indexes.MultiValueField()
    file      = indexes.CharField(model_attr='file')
    filesize  = indexes.IntegerField(model_attr='file__size')
    timestamp = indexes.DateTimeField(model_attr='timestamp')
    url       = indexes.CharField(model_attr='page')

    def prepare_attrs(self, obj):
        """ Prepare the attributes for any file attachments on the
            current page as specified in the M2M relationship. """
        # Add in attributes (assuming there's a M2M relationship to
        # attachment attributes on the model.) Note that this will NOT
        # get picked up by the automatic schema tools provided by haystack
        attributes = obj.attributes.all()
        return attributes

在我的模板 View 中利用它:

    {% if result.attrs|length %}
    <div class="attributes">
        <ul>
        {% for a in result.attrs %}
            <li class="{% cycle "clear" "" "" %}"><span class="name">{{ a.name }}</span>: <span class="value">{{ a.value }}</span></li>
        {% endfor %}
        </ul>
        <div class="clear"></div>
    </div>
    {% endif %}

这似乎对我没有任何返回:(

最佳答案

实际问题是 M2M 字段未在搜索引擎中编制索引。您应该在 prepare_ 函数中返回原始对象(列表、字符串、整数等),而不是 Django Moldel 实例。

例如


def prepare_attr(self, obj): 
  return [str(v) for v in obj.attrs.all()]

关于python - 使用 Django haystack MultiValueField 迭代搜索结果 View 中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4000482/

相关文章:

python - Django 1.7 出现 ImportError,无法导入名称模式

android - 如何将适配器设置为自动完成 TextView ?

magento - 如何将我的 Magento 迷你搜索表单移动到模板标题中的另一个位置?

python - 类构造函数列表在整个 Python 代码中保持为空

python - numpy 数组的 bool /非零索引循环的替代方案

python - PyCryptodome 错误 : MAC Check Failed

python - 在 Django 中检索周一到周五的行?

python - django如何在filter中实现双下划线?

javascript - 查找具有特定文本的 DOM 元素并修改它

python Pandas : diff by user in a DataFrame containing multiple users