Using django-haystack, how do I order results by content type

十年热恋 提交于 2019-12-07 09:07:00

问题


I'm using django-haystack for a search page on my site, and I want to order all the results by their content type. Is there a way I can do that? To make it simpler, suppose I have a single application and several classes. Thanks in advance


回答1:


from How to order search results by Model:

You can do SearchQuerySet().order_by('django_ct'). As a warning, this throws out relevancy. The only way to keep relevancy & group by model is either to run many queries (one per model - usually performant thanks to query caching) or to run the query and post-process the results, regrouping them as you go.

from searchindex api:

Haystack reserves the following field names for internal use: id, django_ct, django_id & content. The name & type names used to be reserved but no longer are.

You can override these field names using the HAYSTACK_ID_FIELD, HAYSTACK_DJANGO_CT_FIELD & HAYSTACK_DJANGO_ID_FIELD if needed.




回答2:


Not sure what you mean by content type, but if you are talking about group by models, I have this working

        {% with page.object_list as results %}
            {% regroup results|dictsort:"verbose_name_plural" by verbose_name_plural as grouped_objects %}
            {% for ct in grouped_objects %}
                {{ ct.grouper }}
                {% for result in ct.list %}
                    <p>
                        <a href="{{ result.object.get_absolute_url }}">{{ result.object }}</a>
                    </p>
                {% endfor %}
            {% empty %}
                <p>No results found.</p>
            {% endfor %}
        {% endwith %}


来源:https://stackoverflow.com/questions/5414632/using-django-haystack-how-do-i-order-results-by-content-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!