djangosearchdjango-urlsdjango-haystack

Django haystack, no url in search results


I have haystack + django + aldryn-search setup for searches on my django-cms project. I am trying to get indexes on my models to work, I can see results and the text description is fine, but the urls are always /search/none. How would I override the url definition?

search_indexes.py:

import datetime
from haystack import indexes
from .models import Event

class EventIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    title = indexes.CharField(model_attr='title')


    def get_model(self):
        return Event

    def index_queryset(self, using=None):
        "Used when the entire index for model is updated."
        return self.get_model().objects.order_by('created')

models.py

class Event(ChangesMixin, models.Model):
    ....
    title = models.CharField(max_length=40)
    ....

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return '/cab/event/%i/' % self.id

Solution

  • I see you're not subclassing the AldrynIndexBase or AbstractIndex base indexes from aldryn-search, this means you'll need to define the url field since you're subclassing haystack's builtin index class which does not come with any fields predefined.

    You can easily add it like so:

    class EventIndex(indexes.SearchIndex, indexes.Indexable):
        url = indexes.CharField(model_attr='get_absolute_url')
    

    Or:

    class EventIndex(indexes.SearchIndex, indexes.Indexable):
        url = indexes.CharField()
    
        def prepare_url(self, obj):
            return obj.get_absolute_url()
    

    I recommend approach number two because approach number one behaves differently if the provided attribute string has double underscores like get__title woul look for event.get.title instead of event.get__title.

    If your Event model supports multiple languages using libraries like django-hvad or django-parler, I highly recommend you use AldrynIndexBaseorAbstractIndexinstead of haystack'sindexes.SearchIndex```.