Created
March 15, 2010 16:17
-
-
Save jacobian/332995 to your computer and use it in GitHub Desktop.
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
import operator | |
from django.db.models import Q | |
def search(model_or_qs, search_fields, search_string): | |
""" | |
Perform a quick and dirty model "search", similar to how the admin's | |
`search_fields` works (see http://tinyurl.com/66xz2n):: | |
>>> search(Entry, ['summary', 'body'], 'content') | |
[...] | |
>>> search(Person.objects.alive(), ['^first_name'], 'J') | |
[...] | |
""" | |
if hasattr(model_or_qs, '_default_manager'): | |
qs = model_or_qs._default_manager.all() | |
else: | |
qs = model_or_qs | |
clauses = [] | |
for field in search_fields: | |
if field.startswith('^'): | |
query = '%s__istartswith' % field[1:] | |
elif field.startswith('='): | |
query = '%s__exact' % field[1:] | |
else: | |
query = '%s__icontains' % field | |
clauses.append(Q(**{query: search_string})) | |
query = reduce(operator.or_, clauses) | |
return qs.filter(query) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment