Query lookups using operators

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class X(object):
    def __init__(self, field):
        self.field = field

    def _eval(self, other, lookup):
        from django.db.models import Q
        return Q(**{ '%s__%s' % ( self.field, lookup ) : other })

    def __eq__(self, other):
        return self._eval(True, 'isnull') if other is None else self._eval(other, 'exact')

    def __ne__(self, other):
        return ~ ( self == other )

    def __lt__(self, other):
        return self._eval(other, 'lt')

    def __le__(self, other):
        return self._eval(other, 'lte')

    def __gt__(self, other):
        return self._eval(other, 'gt')
    
    def __ge__(self, other):
        return self._eval(other, 'gte')

    def __mod__(self, other):
        return self._eval(other, 'icontains')

    def __lshift__(self, other):
        return self._eval(other, 'istartswith')

    def __rshift__(self, other):
        return self._eval(other, 'iendswith')

    def __or__(self, other):
        return self._eval(other, 'in')

More like this

  1. baseconv.py - convert base 10 integers to base X and back again by simon 5 years ago
  2. Lazily lookup dynamically for templates by axiak 6 years, 1 month ago
  3. versioned_media templatetag by dnordberg 5 years, 8 months ago
  4. Sphinx Search ORM by zeeg 6 years, 11 months ago
  5. Get derived model instance by werehuman 7 months ago

Comments

artur_mwaigaryan (on November 14, 2011):

great snippet!

#

(Forgotten your password?)