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
- Function/Stored Procedure Manager by axiak 6 years ago
- Yet another query string template tag by atms 2 years, 2 months ago
- decorator to synchronize method at class / module level by mwolgemuth 4 years, 4 months ago
- function tracing decorator by amitu 4 years, 3 months ago
- Automatic Memoization Decorator by nikmolnar 5 months, 2 weeks ago
Comments
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.
#