Login

Query lookups using operators

Author:
diverman
Posted:
August 4, 2010
Language:
Python
Version:
1.2
Tags:
q query lookup operator
Score:
2 (after 4 ratings)

This class emulates query lookups to behave as numeric operators. Inspired by SQLAlchemy.

User.objects.filter( X('username') == 'diverman' )
User.objects.filter( X('username') != 'diverman' )
User.objects.filter( X('pk') > 10 )
User.objects.filter( X('pk') >= 10 )
User.objects.filter( X('pk') < 10 )
User.objects.filter( X('pk') <= 10 )
User.objects.filter( X('username') % 'iverma' )
User.objects.filter( X('username') << 'diver' )
User.objects.filter( X('username') >> 'man' )
User.objects.filter( X('pk') | (1, 2, 3) )
 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, 10 months ago
  2. Lazily lookup dynamically for templates by axiak 6 years, 11 months ago
  3. versioned_media templatetag by dnordberg 6 years, 6 months ago
  4. Sphinx Search ORM by zeeg 7 years, 9 months ago
  5. Get derived model instance by werehuman 1 year, 5 months ago

Comments

artur_mwaigaryan (on November 14, 2011):

great snippet!

#

Please login first before commenting.