Code


Version 1 (modified by jason.mcveta@…, 7 years ago) (diff)

--

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