Houman
Houman

Reputation: 66320

Django-Haystack : How to limit search to objects owned by user?

I have successfully made django-haystack with elasticsearch to work. In the example below, I can search for any sales item and it would show up in the results.

I have created an Index:

class SalesItemIndex(SearchIndex, Indexable):
    text = CharField(document=True, use_template=True)
    item_description = CharField(model_attr='item_description')

    def get_model(self):
        return SalesItem

    def index_queryset(self):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

The model SalesItem:

class SalesItem(models.Model):        
    item_description    = models.CharField(_(u"Item Description"), max_length=40)
    company             = models.ForeignKey(Company)
    def __unicode__(self):
        return self.item_description

The problem is though, the user can search for all sales items, even those that don't belong to his company.

Usually instead of returning all salesitems = SalesItem.objects.all() I would rather use this to make sure the user only sees the items that belons to his company:

profile = request.user.get_profile() 
sales_items = profile.company.salesitem_set.all() 

Would I be able to limit my search with this rule?

Upvotes: 1

Views: 693

Answers (1)

okm
okm

Reputation: 23871

You could index the company id in the SalesItemIndex as well:

class SalesItemIndex(SearchIndex, Indexable):
    ...
    company = IntegerField(model_attr='company_id')

And filter it directly in SearchQuerySet:

sales_items = salesitem_set.filter(company=profile.company_id)

Upvotes: 0

Related Questions