Created
May 17, 2015 16:24
-
-
Save anonymous/154512b369fe7e273631 to your computer and use it in GitHub Desktop.
A method to combine SQL and ORM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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