Code

Changes between Initial Version and Version 1 of OrQueryBuilder


Ignore:
Timestamp:
08/14/07 14:03:49 (7 years ago)
Author:
jason.mcveta@…
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • OrQueryBuilder

    v1 v1  
     1Sometimes 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: 
     2 
     3{{{ 
     4#!python 
     5def buildOrQuery(request, config): 
     6        ''' 
     7        Builds a django.db.models.query.QOr object based on HTTP request and a 
     8        simple config dictionary, mapping field names to filter syntax.  For 
     9        example: 
     10        config = { 
     11                'bar': 'foo__bar__exact', 
     12                'ham': 'spam__eggs__ham__icontains', 
     13        } 
     14        ''' 
     15        query = None # A blank query here would be v bad 
     16        for field in config.keys(): 
     17                values = request.POST.getlist(field) 
     18                for value in values: 
     19                        subquery = Q(**{config[field]: value}) 
     20                        if not query: 
     21                                query = subquery 
     22                        else: 
     23                                # Combine using OR: 
     24                                query = query | subquery 
     25        if query: 
     26                return query 
     27        else: 
     28                return Q() # Blank query -- it would break things to return None 
     29}}}