filtering for multiple values in a MultiValueField in Django Haystack
Asked Answered
L

1

7

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?

Litman answered 18/11, 2013 at 21:50 Comment(0)
L
13

It looks like the correct way to do this is:

SearchQuerySet().models(Object).filter(groups__in=[g.id for g in aperson.groups.all()])
Litman answered 18/11, 2013 at 22:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.