开发者

Django Haystack/Solr: Faceting on a model but show results only from a ForeignKey field

I have two models in Django like follows(in pseudo code)

class Medicine(db.Model):
    field_1 = db.CharField()
开发者_高级运维    field_2 = db.CharField()

class Application(db.Model):
    field_1 = db.CharField()
    field_2 = db.CharField()
    medicine = db.ForeignKey(Medicine)

There is a 1:M. One medicine can have many applications.

I need to facet on the fields of Application but only show related Medicine objects. Something like DISTINCT in SQL.

What would be the most straight forward way to accomplish this with haystack?

Do I make SearchIndex for Medicine or Application? If I make SearchIndex for Application, how do I detect/filter duplicate Medicine objects?

PS: I know there's Field Collapsing feature in dev releases of Solr, but I want to avoid doing that, becuase it is huge database and performance critical.


I solved this with the help of Daniel Lindsay(Haystack/pySolr author) on haystack mailing list.

from haystack import indexes

class Medicine(indexes.SearchIndex):
    field_1 = indexes.MultiValuedField(faceted=True)
    # Other field definitions


    def prepare_field_1(self, object):
        values = list()
        for app in object.applications.all():
            values.append(app.field_on_which_to_facet)
        return values

    # define "prepare_fieldname" methods for other fields in similar fashion.

Indexing takes some time as the data to be indexed is huge is huge, but worked like a charm.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜