I want to facet the results based on the different model_names (classes) returned. Is there an easy way to do this?
问题:
回答1:
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.
回答2:
The Docs have a really good walk-through for this.
The minimum you'll need:
- is to add
faceted=True
to the params of yourmodel_names
field. - Rebuild your schema and indices.
- add
.facet('model_names')
to whatever SearchQuerySet you're wanting to facet.
More explanation on the question would enable a more complete answer.
回答3:
If you just want to filter on the model type, you can use the ModelSearchForm