Created
April 19, 2012 23:24
-
-
Save mattdw/2424828 to your computer and use it in GitHub Desktop.
A simple functional search query creator for Django.
This file contains hidden or 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.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