Login

SQL Function Decorator

Author:
proc
Posted:
August 23, 2008
Language:
Python
Version:
.96
Score:
-1 (after 3 ratings)

This decorator will replace a method on a model with a class method that executes SQL in the functions doc string.

 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
def SQL(*keys):
    def _SQL(func):
        def _sqlfunc(cls, *args):
            from django.db import connection
            cursor = connection.cursor()
            cursor.execute(func.__doc__, args)
            rv = cursor.fetchall()

            if keys:
                rv = [dict(zip(keys, i)) for i in rv]

            return rv

        return classmethod(_sqlfunc)
    return _SQL

#EXAMPLE
@SQL('foo', 'bar', 'baz')
def foo(cls):
    '''SELECT foo, AVG(bar) AS bar, AVG(baz) AS baz
       FROM foos
       WHERE quuux=%s
       GROUP BY foo
       ORDER BY foo'''

#INVOCATION
Foo.foo(1)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

phxx (on August 24, 2008):

It is no good solution to provide semantic code in the doc string. It exists only for documentation.

But maybe you can return the SQL query as a string from the foo function.

#

Please login first before commenting.