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. Bitwise operator queryset filter by hgeerts@osso.nl 3 years ago
  2. Lazily lookup dynamically for templates by axiak 5 years, 2 months ago
  3. CustomQueryManager by zvoase 4 years, 10 months ago
  4. Prefill ForeignKey caches by insin 4 years, 7 months ago
  5. caching parsed templates by forgems 5 years, 5 months ago

Comments

artur_mwaigaryan (on November 14, 2011):

great snippet!

#

(Forgotten your password?)