結果我目前使用Django 1.10.3,與elasticsearch後端的Django乾草堆的搜索引擎,並DRF-草垛證明的意見。過濾DRF-草垛當前用戶
一般的搜索已經很大,但我完全無法用當前用戶對搜索結果進行過濾。
該指數是:
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()
的視圖(也包括HaystackSerializer,但其通用的,值得包括)。
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')
最後,過濾器:
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
部分具有teacherprofiles的M2M領域,我基本上要確保結果只包含部分老師那裏是監事。
此實現返回所有匹配的查詢,但忽略了過濾條件,沒有拋出任何類型的錯誤。
「最好」的結果,我已經得到了通過嘗試來惹視圖filter_queryset,加入.filter(監事=教師)的查詢集,但返回我所有的部分與老師作爲導師,加上與查詢相匹配的所有課程,而不管主管的狀態如何。