Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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