Skip to content

Instantly share code, notes, and snippets.

@lowkeyshift
Created July 17, 2019 01:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lowkeyshift/9c3e2a0c9b012f9d8dd1a56bf85214b5 to your computer and use it in GitHub Desktop.
Save lowkeyshift/9c3e2a0c9b012f9d8dd1a56bf85214b5 to your computer and use it in GitHub Desktop.
from django.db.models import Case, ExpressionWrapper, IntegerField, Q, Value, When
class SpecialSearch(ListAPIView):
model = Object
serializer_class = ObjectSerializer
def get_queryset(self, rs, value):
"""
Recipe search matching, best matching and kind of matching,
by filtering against `tags` query parameter in the URL.
"""
if value:
tags = [tag.strip() for tag in value.split(',')]
qs = Object.objects.filter(
reduce(
lambda x, y: x | y, [Q(tags__icontains=tag) for tag in tags]))
check_matches = map(
lambda x: Case(
When(Q(tags__icontains=x), then=Value(1)),
default=Value(0)),
tags)
count_matches = reduce(lambda x, y: x + y, check_matches)
qs = qs.annotate(
matches=ExpressionWrapper(
count_matches,
output_field=IntegerField()))
qs = qs.order_by('-matches')
return qs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment