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
        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
                                # Combine using OR:
                                query = query | subquery
        if query:
                return query
                return Q() # Blank query -- it would break things to return None
Last modified 8 years ago Last modified on 08/14/07 16:03:49
Back to Top