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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.