问题
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