Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filtering for multiple values in a MultiValueField in Django Haystack

I've got two models like below. The permission structure allows a Person to see any object that has a Group in common with them, so that if a Person is in Groups 1, 2, and 3, and an Object is shared with Groups 3, 4, 5, the Person can see it through Group 3.

class Person(models.Model):
    groups = models.ManyToManyField(Group)

class Object(models.Model):
    groups = models.ManyToManyField(Group)

The SearchIndex is like this:

class ObjectIndex(indexes.SearchIndex, indexes.Indexable):
    groups = indexes.MultiValueField(null=True)

    def prepare_groups(self, obj):
        return [group.pk for group in obj.groups.all()] or None

So, what is the best way to create a SearchQuerySet that allows me to take something like SearchQuerySet().models(Object).filter(groups=aperson.groups.all()) that is an OR on the groups instead of an AND?

like image 898
mrooney Avatar asked Nov 18 '13 21:11

mrooney


1 Answers

It looks like the correct way to do this is:

SearchQuerySet().models(Object).filter(groups__in=[g.id for g in aperson.groups.all()])
like image 125
mrooney Avatar answered Nov 09 '22 02:11

mrooney