Django-Haystack: ¿Cómo limitar la búsqueda a objetos propiedad del usuario?

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?

preguntado el 28 de agosto de 12 a las 10:08

1 Respuestas

You could index the company id in the SalesItemIndex también:

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)

Respondido 28 ago 12, 14:08

This sounds promising. Is my assumption correct that I need to roll my own SearchForm in order to access the SearchQuerySet and do what you suggested? - Houman

@Kave if you mean haystack.forms.SearchForm, es compatible searchqueryset in __init__. Entonces algo como SearchForm(searchqueryset=sqs) is fine. Also, I'd like to define a get_searchqueryset() method on the corresponding Django Model for convenience. - OK M

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.