Created
October 30, 2017 18:59
-
-
Save souldeux/5279bd8639713f4e50e6e2453207b2bc to your computer and use it in GitHub Desktop.
Basic Full-Text Postgres Search Mixin for Django Class-Based Views
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.postgres.search import SearchVector | |
class BaseSearchMixin(object): | |
""" | |
Implements postgres full-text search engine for programmer-defined fields. | |
Expects self.search_fields, a tuple containing an arbitraty number of fields | |
to be used in the search. These should be defined in the view into which | |
this is mixed, and should correpsond to available text/char fields on the | |
model on which that view operates. | |
If the view is called with a URL querystring argument called "search", we use | |
the value of that argument to filter against a SearchVector. We construct | |
a new SearchVector like so: | |
SearchVector(*self.search_fields) | |
We annotate our queryset with this new search vector, then We then use the value | |
of self.request.GET['search'] to filter against this annotation. | |
""" | |
search_fields = () | |
def get_queryset(self): | |
queryset = super(BaseSearchMixin, self).get_queryset() | |
if not self.search_fields or self.request.GET.get('search', None) is None: | |
return queryset | |
return queryset.annotate( | |
search = SearchVector(*self.search_fields) | |
).filter( | |
search = self.request.GET['search'] | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment