superSearch function for generating large OR queries

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from django.db.models.query import Q
def superSearch(model, fields, matches, strings):
	"""
	Designed to lessen the code needed to run complex searches with ORed filters.  
	Model: the model being queried.
	fields: an iterable containing string names of fields to query.
	match:  an iterable containing strings of what type of Django lookup to apply to those fields.
	strings: an iterable containing strings to be matched.
	"""
	queries = []
	for field in fields:
		for string in strings:
			for match in matches:
				kwargs = {'%s__%s' % (field, match): string}
				queries.append(Q(**kwargs))
	q = Q()
	for query in queries:
		q = q | query
	return model.objects.filter(q)

More like this

  1. format output as table by bendavis78 4 years, 9 months ago
  2. UserProfileForm by Natim 4 years, 5 months ago
  3. Debug middleware for displaying sql queries and template loading info when ?debug=true by SEJeff 3 years ago
  4. update_or_create by abhin4v 5 years, 6 months ago
  5. Yet another query string template tag by atms 3 years ago

Comments

rix (on August 11, 2009):

This is nice! Maybe you could remove the last loop, something like this:

def superSearch(model, fields, matches, strings):
    q = Q()
    for field in fields:
        for string in strings:
            for match in matches:
                kwargs = {'%s__%s' % (field, match): string}
                q = q | Q(**kwargs)
    return model.objects.filter(q)

#

(Forgotten your password?)