1
我已经用elasticsearch成功制作了django-haystack。 在下面的例子中,我可以搜索任何销售项目,并且它会显示在结果中。Django-Haystack:如何限制搜索到用户拥有的对象?
我创建了一个索引:
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()
模型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
的问题是,虽然,用户可以搜索所有销售的项目,即使是那些不属于他的公司。
通常,而不是返回所有salesitems = SalesItem.objects.all()
我宁愿用这个来确保用户只能看到该belons到他的公司的项目:
profile = request.user.get_profile()
sales_items = profile.company.salesitem_set.all()
请问我可以限制我的这个规则搜索?
这听起来前途。我的假设是否正确,我需要推出自己的SearchForm才能访问SearchQuerySet并执行您的建议? – Houman
@Kave如果你的意思是'haystack.forms.SearchForm',它支持'__init__'中的'searchqueryset'。所以像'SearchForm(searchqueryset = sqs)'就好了。另外,为了方便起见,我想在相应的Django模型上定义一个'get_searchqueryset()'方法。 – okm