代码之家  ›  专栏  ›  技术社区  ›  nyxtom

使用Django haystack多值字段迭代搜索结果视图中的项

  •  6
  • nyxtom  · 技术社区  · 14 年前

    如果我的一个搜索索引上有一个多值字段,并且我想在搜索结果中显示每个值,我该如何做?似乎有些东西的格式不合适,或者我不知怎么误解了多值字段?

    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
    

    在我的模板视图中利用此功能:

        {% 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 %}
    

    这对我来说似乎什么都没有:(

    1 回复  |  直到 9 年前
        1
  •  1
  •   Nicolae Dascalu    13 年前

    实际问题是搜索引擎中没有索引M2M字段。应该在prepare_u函数中返回基元对象(list、string、int等),而不是Django Moldel实例。

    例如

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