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