Sometimes one may wish to query the database for objects matching any of several criteria specified in several form fields, some of which may be multiple choice. This function makes that easy:
def buildOrQuery(request, config): ''' Builds a django.db.models.query.QOr object based on HTTP request and a simple config dictionary, mapping field names to filter syntax. For example: config = { 'bar': 'foo__bar__exact', 'ham': 'spam__eggs__ham__icontains', } ''' query = None # A blank query here would be v bad for field in config.keys(): values = request.POST.getlist(field) for value in values: subquery = Q(**{config[field]: value}) if not query: query = subquery else: # Combine using OR: query = query | subquery if query: return query else: return Q() # Blank query -- it would break things to return None
Last modified
17 years ago
Last modified on Aug 14, 2007, 4:03:49 PM
Note:
See TracWiki
for help on using the wiki.