简体   繁体   中英

How to group Haystack search results in Django

I'm trying to group search results from Haystack. I want them to be grouped by model (Artist or Painting), then by a date field (created), then ideally by a boolean field (sold).

Ie something like the following but it's not working. I think I need to override SearchView and somehow process the query before it's handed to the template but I'm not sure how.

Or perhaps I should just be doing the grouping in the template?

def get_queryset():
    q = SearchQuerySet().filter(display=True).order_by('-created')

    paintings_unsold = q.models(Painting).filter(sold=False)
    paintings_sold = q.models(Painting).filter(sold=True)
    artists = q.models(Artist)

    return paintings_unsold | paintings_sold | artists


urlpatterns += patterns(
    '',
    (r'^search/', SearchView(
         searchqueryset=get_queryset()
    ))
)

Just to clarify that facetting is not equal to grouping results. SOLR can do this, for example (Version 4): https://cwiki.apache.org/confluence/display/solr/Result+Grouping .

But what you are actually asking for is faceting, as mentioned in the comments:

http://django-haystack.readthedocs.org/en/v2.4.0/faceting.html https://cwiki.apache.org/confluence/display/solr/Faceting

I will provide an answer for SOLR, even thought the question is tagged with Whoosh. It might still help.


You want to facet on the field sold and a field artist_exact that you will probably have to create. It has to be of type string otherwise your facets will look odd.

So, your current artist field is probably (recommended) a text field that tokenizes the input somehow. Simply add a new field that does not tokenize and a copy directive in schema.xml that copies the artist to this new field.

<field name="artist" type="text_general" indexed="true" stored="true"/>
<field name="artist_exact" type="string" indexed="true" stored="false"/>
<copyField source="artist" dest="artist_exact" />

In solrconfig.xml add the following parameters to your search handler:

<str name="facet">on</str>
<str name="facet.field">sold</str>
<str name="facet.field">artist_exact</str>

Haystack provides the FacetedSearchView that you can use. It will add the facet information to the template context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM