Login

Query lookups using operators

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

Comments

artur_mwaigaryan (on November 14, 2011):

great snippet!

#

Please login first before commenting.