Reputation: 51
I'm currently using Django 1.10.3, django-haystack search engine with elasticsearch backend, and drf-haystack to prove the views.
The searches in general have been great, but I am completely unable to filter results by current user.
The index is:
class SectionIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.EdgeNgramField(document=True, use_template=True, template_name="indexes/structure_text.txt")
pkey = indexes.IntegerField(model_attr='pk')
title = indexes.CharField()
for the view (also includes HaystackSerializer, but its generic and not worth including).
class SectionSearchView(HaystackViewSet):
index_models = [Section]
serializer_class = SectionViewSerializer
pagination_class = None
filter_backend = SectionFilter
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def filter_queryset(self, queryset):
queryset = super(HaystackGenericAPIView, self).filter_queryset(queryset)
return queryset.using('section')
And lastly, the filter:
class SectionFilter(HaystackFilter):
mine = django_filters.MethodFilter(action='get_mine')
class Meta:
model = Section
fields = ['mine']
def get_mine(self, queryset, value):
try:
teacher = self.request.user.teacherprofile
return queryset.filter(supervisors=teacher)
except:
return queryset
Section has an M2M field with teacherprofiles, and I basically want to make sure the results ONLY contain the sections where the teacher is in the supervisors.
This implementation returns all matching queries, but ignores the filter condition, without throwing any sort of an error.
The "best" result I've gotten was by trying to mess with filter_queryset in the view, adding a .filter(supervisors=teacher) to the queryset, but that returned me ALL the sections with the teacher as supervisor, PLUS all the courses matching the query, regardless of supervisor status or not.
Upvotes: 1
Views: 681
Reputation: 51
So at the end of the day, to whom it may concern, I eventually used a SearchQuerySet to return results for the classes, then convert the results to a list and removing the items without the teacher as a supervisor.
It's probably not the most efficient way, and I wasnt able to get it working within Haystack alone (even using SQS with the filter_and(name, supervisor) conditions), but it works, and still performs more than well enough performance wise.
Upvotes: 2