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

 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. JSON-compatible query filter specification by mhalle 5 years, 1 month ago
  2. Dynamic query builder with AND/OR by bobwaycott 3 years, 9 months ago
  3. Filter on Multiple M2M Objects Simultaneously by axiak 6 years, 1 month ago
  4. Bitwise operator queryset filter by hgeerts@osso.nl 3 years ago
  5. CustomQueryManager by zvoase 4 years, 10 months ago

Comments

(Forgotten your password?)