Login

make a combined set of db.Q objects out of a list of dicts and an operator

Author:
jdunck
Posted:
January 24, 2012
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

It's often useful to dynamically create filter criteria, and Q objects are useful for that, but sometimes you need to make a combined Q composed of various alternates. This bit of code eases the awkwardness of creating the first Q so that there's a combiner, plus the odd case of no criteria.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.db.models import Q

def make_q(operator, criteria):
    """
    Concatenates Q objects for criteria, which is a list of dicts.
    This centralizes this goofy awkwardness of handling the first item 
      differently than the remaining items.

    >>> print make_q(operator.or_, [{'x':1, 'y':2}, {'y': 3}])
    (OR: ('y', 3), (AND: ('y', 2), ('x', 1)))
    """
    criteria = list(criteria) # copy
    # Errors should never pass silently.
    #...
    #In the face of ambiguity, refuse the temptation to guess.
    if not criteria:
        raise ValueError("Refusing to make an empty Q object (no criteria)")

    q_ = Q(**criteria.pop())
    for criterion in criteria:
        q_ = operator(q_, Q(**criterion))
    return q_

More like this

  1. "Magic Link" Management Command by webology 3 months ago
  2. Closest ORM models to a latitude/longitude point by simonw 3 months ago
  3. Log the time taken to execute each DB query by kennyx46 3 months ago
  4. django database snippet by ItsRLuo 3 months, 1 week ago
  5. Serialize a model instance by chriswedgwood 4 months ago

Comments

Please login first before commenting.