Skip to content

Instantly share code, notes, and snippets.

@mattdw
Created April 19, 2012 23:24
Show Gist options
  • Save mattdw/2424828 to your computer and use it in GitHub Desktop.
Save mattdw/2424828 to your computer and use it in GitHub Desktop.
A simple functional search query creator for Django.
from django.db.models import Q
from django.utils.text import smart_split
def get_or_query(query_string, fields):
return reduce(Q.__or__,
(Q(**{'%s__iregex' % field: r"[[:<:]]%s" % term.strip('\'"')})
for term in smart_split(query_string) if term not in ['and', 'or']
for field in fields),
Q())
def get_and_query(query_string, fields):
return reduce(Q.__and__,
(reduce(Q.__or__,
(Q(**{'%s__iregex' % field: r"[[:<:]]%s" % term.strip('\'"')})
for field in fields),
Q()) for term in smart_split(query_string) if term not in ['and', 'or']),
Q())
## Use like:
results = SomeModel.objects.filter(get_or_query("an interesting 'search query'", ["name", "description", "summary"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment