Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Haystack faceting on the model type

I want to facet the results based on the different model_names (classes) returned. Is there an easy way to do this?

like image 593
asawilliams Avatar asked Jul 24 '11 21:07

asawilliams


1 Answers

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.

like image 54
bennylope Avatar answered Oct 30 '22 18:10

bennylope