Skip to content

Instantly share code, notes, and snippets.

@alex
Forked from jacobian/modelsearch.py
Created March 15, 2010 19:10
Show Gist options
  • Save alex/333203 to your computer and use it in GitHub Desktop.
Save alex/333203 to your computer and use it in GitHub Desktop.
import operator
from django.db.models import Q
from django.shortcuts import _get_queryset
def search(klass, 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')
[...]
"""
qs = _get_queryset(klass)
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