6
如果我在其中一個搜索索引中有一個MultiValueField,並且我想在搜索結果中顯示每個值,那麼我該怎麼做?這似乎是某些東西沒有被正確格式化,或者我在某種程度上誤解了MultiValueField?使用Django乾草堆對搜索結果視圖中的項目進行迭代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
在我的模板視圖利用此:
{% 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 %}
這似乎對我來說什麼都不返回:(