Django-Haystack:如何将搜索限制为用户拥有的对象?

时间:2022-11-03 19:38:15

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.

我已经成功地使用elasticsearch进行django-haystack工作。在下面的示例中,我可以搜索任何销售项目,它将显示在结果中。

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:

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:

通常不是返回所有的salesitems = SalesItem.objects.all()而是使用它来确保用户只看到与他的公司有关的项目:

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

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

我可以使用此规则限制搜索吗?

1 个解决方案

#1


1  

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

您也可以在SalesItemIndex中索引公司ID:

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

And filter it directly in SearchQuerySet:

并在SearchQuerySet中直接过滤它:

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

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

#1


1  

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

您也可以在SalesItemIndex中索引公司ID:

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

And filter it directly in SearchQuerySet:

并在SearchQuerySet中直接过滤它:

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

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