Add member search api route

This commit is contained in:
2020-01-11 00:47:13 +00:00
parent fddaf083b4
commit 402ec28ff5
6 changed files with 76 additions and 0 deletions
+49
View File
@@ -3,6 +3,8 @@ from django.db.models import Max
from rest_framework import viewsets, views, permissions
from rest_framework.response import Response
from rest_auth.registration.views import RegisterView
from fuzzywuzzy import fuzz, process
from collections import OrderedDict
from . import models, serializers
@@ -16,6 +18,53 @@ class UserViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserSerializer
search_strings = {}
def gen_search_strings():
for m in models.Member.objects.all():
string = '{} {} {} {}'.format(
m.preferred_name,
m.last_name,
m.first_name,
m.last_name,
).lower()
search_strings[string] = m.id
gen_search_strings()
class SearchViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = [AllowMetadata | permissions.IsAuthenticated]
serializer_class = serializers.OtherMemberSerializer
def get_queryset(self):
NUM_SEARCH_RESULTS = 10
queryset = models.Member.objects.all()
params = self.request.query_params
if 'q' in params and len(params['q']) >= 3:
search = params['q'].lower()
choices = search_strings.keys()
# get exact starts with matches
results = [x for x in choices if x.startswith(search)]
# then get exact substring matches
results += [x for x in choices if search in x]
# then get fuzzy matches
fuzzy_results = process.extract(search, choices, limit=NUM_SEARCH_RESULTS, scorer=fuzz.token_set_ratio)
results += [x[0] for x in fuzzy_results]
# remove dupes
results = list(OrderedDict.fromkeys(results))
result_ids = [search_strings[x] for x in results]
result_objects = [queryset.get(id=x) for x in result_ids]
queryset = result_objects
else:
queryset = queryset.order_by('-vetted_date')
return queryset[:NUM_SEARCH_RESULTS]
class MemberViewSet(viewsets.ModelViewSet):
permission_classes = [AllowMetadata | permissions.IsAuthenticated]
http_method_names = ['options', 'head', 'get', 'put', 'patch']