filtering for multiple values in a MultiValueField in Django Haystack

扶醉桌前 提交于 2019-12-23 09:31:03

问题


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?


回答1:


It looks like the correct way to do this is:

SearchQuerySet().models(Object).filter(groups__in=[g.id for g in aperson.groups.all()])


来源:https://stackoverflow.com/questions/20058693/filtering-for-multiple-values-in-a-multivaluefield-in-django-haystack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!