Search code examples
pythondjangosolrdjango-haystackdatefield

Django / haystack - faceting based only on the year element of a DateField


Say I have the following model in a Django implementation:

class Broadcast(models.Model):
    broadcast_date = models.DateField()
    ...

In my haystack/Solr-driven search results, I'd like to be able to facet by solely the year of broadcast, not the exact day.

I could just make a new model attribute for this, but it seems like I should be able to do this in the search_indexes model definition somehow. Here is what I have in search_indexes.py at the moment, which facets by the full date only:

class BroadcastIndex(indexes.SearchIndex, indexes.Indexable):
    text = [...]
    broadcast_date = indexes.DateField(model_attr="broadcast_date", faceted=True)

Any ideas?


Solution

  • You should be able to use date_facet(). If you set it's gap_by parameter to year, it will facet by year.