Skip to content

Instantly share code, notes, and snippets.

@LegoStormtroopr
Created October 9, 2014 00:20
Show Gist options
  • Save LegoStormtroopr/e0a8a854cf07d46d675f to your computer and use it in GitHub Desktop.
Save LegoStormtroopr/e0a8a854cf07d46d675f to your computer and use it in GitHub Desktop.
Haystack google-like colon searching
# Released as GPL.
# Attribute where possible :)
from haystack.constants import DEFAULT_ALIAS
from haystack import connections
class TokenSearchForm(SearchForm):
def prepare_tokens(self):
try:
query = self.cleaned_data.get('q')
except:
return {}
opts = connections[DEFAULT_ALIAS].get_unified_index().fields.keys()
kwargs = {}
query_text = []
for word in query.split(" "):
if ":" in word:
opt,arg = word.split(":",1)
if opt in opts:
kwargs[str(opt)]=arg
else:
query_text.append(word)
self.query_text = " ".join(query_text)
self.kwargs = kwargs
return kwargs
def search(self):
self.query_text = None
kwargs = self.prepare_tokens()
if not self.is_valid():
return self.no_query_found()
if not self.cleaned_data.get('q'):
return self.no_query_found()
sqs = self.searchqueryset.auto_query(self.query_text)
if kwargs:
sqs = sqs.filter(**kwargs)
if self.load_all:
sqs = sqs.load_all()
return sqs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment