使用Django haystack MultiValueField迭代搜索结果视图中的项目

时间:2021-12-30 18:15:09

If I have a MultiValueField on one of my search indexes, and I want to display each value in the search results, how would I do that? It seems like something is not being formatted appropriately or I am somehow misunderstanding the MultiValueField?

如果我的一个搜索索引上有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

In leveraging this in my template 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 %}

This seems to return nothing for me :(

这似乎没有给我任何回报:(

1 个解决方案

#1


1  

The actual issue is that the M2M field is not indexed in SearchEngine. You should return primitive objects( list, string, int, etc.) in the prepare_ function and not Django Moldel instances.

实际问题是M2M字段未在SearchEngine中编入索引。您应该在prepare_函数中返回原始对象(list,string,int等),而不是Django Moldel实例。

e.g.


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

#1


1  

The actual issue is that the M2M field is not indexed in SearchEngine. You should return primitive objects( list, string, int, etc.) in the prepare_ function and not Django Moldel instances.

实际问题是M2M字段未在SearchEngine中编入索引。您应该在prepare_函数中返回原始对象(list,string,int等),而不是Django Moldel实例。

e.g.


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