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
Tags:
orm filtering Q
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. Filter on Multiple M2M Objects Simultaneously by axiak 8 years, 1 month ago
  2. Q marshaller by SpikeekipS 7 years, 2 months ago
  3. CustomQueryManager by zvoase 6 years, 10 months ago
  4. Convert Q object to function by spenczar 2 years, 9 months ago
  5. JSON-compatible query filter specification by mhalle 7 years, 1 month ago

Comments

Please login first before commenting.