Iterating elements in a search result view using haystack Django MultiValueField

If I have a MultiValueField in one of my search indexes and I want to display each value in the search results, how would I do it? It seems that something is not formatted properly, or for some reason I misunderstand 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 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 

Using 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 to me :(

+6
python django search django-haystack
source share
1 answer

The actual problem 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 in Django Moldel instances.

eg.

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

All Articles