Skip to content

Instantly share code, notes, and snippets.

Created May 17, 2015 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/154512b369fe7e273631 to your computer and use it in GitHub Desktop.
Save anonymous/154512b369fe7e273631 to your computer and use it in GitHub Desktop.
A method to combine SQL and ORM
import itertools
from django.db import connection
"""
Combine SQL and ORM.
sql = 'SELECT * FROM ( {} ) T1 NATURAL FULL OUTER JOIN ( {} ) T2; '
querysets = [
MyModel1.objects.filter(...),
MyModel2.objects.filter(...),
]
cursor = execute_orm_sql_query(sql, querysets)
"""
def sqlparams_from_queryset(qs):
"""
Returns the SQL query and params of a queryset.
"""
(qstr, params) = qs.query.sql_with_params()
return (qstr, params)
def execute_orm_sql_query(sqltemplate, querysets):
"""
Combine the Raw SQL with Django ORM query output and execute the query.
Returns the database cursor.
"""
sqlparams = [ sqlparams_from_queryset(qs) for qs in querysets ]
(sqls, params) = zip(*sqlparams) # zip(*...) is the inverse of zip
params = tuple(itertools.chain.from_iterable(params))
cursor = connection.cursor()
cursor.execute(sqltemplate.format(*sqls), params)
return cursor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment