Django Haystack faceting on the model type

爷,独闯天下 提交于 2019-12-05 10:59:31

Have you tried adding a SearchIndex field with this information? E.g.

class NoteIndex(SearchIndex, indexes.Indexable):
    title = CharField(model_attr='title')
    facet_model_name = CharField(faceted=True)

    def get_model(self):
        return Note

    def prepare_facet_model_name(self, obj):
        return "note"


class MemoIndex(SearchIndex, indexes.Indexable):
    title = CharField(model_attr='title')
    facet_model_name = CharField(faceted=True)

    def get_model(self):
        return Memo

    def prepare_facet_model_name(self, obj):
        return "memo"

And so on, simply returning a different string for each search index. You could also create a mixin and return the name of the model returned by get_model too.

Presuming you've added this field to each of your SearchIndex definitions, just chain the facet method to your results.

results = form.search().facet('facet_model_name')

Now the facet_counts method will return a dictionary with the faceted fields and count of results for each facet value, in this case, the model names.

Note that the field here is labeled verbosely to avoid a possible conflict with model_name, a field added by Haystack. It's not faceted, and I'm not sure if duplicating it will cause a conflict.

The Docs have a really good walk-through for this.

The minimum you'll need:

  1. is to add faceted=True to the params of your model_names field.
  2. Rebuild your schema and indices.
  3. add .facet('model_names') to whatever SearchQuerySet you're wanting to facet.

More explanation on the question would enable a more complete answer.

If you just want to filter on the model type, you can use the ModelSearchForm

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