Skip to content

Instantly share code, notes, and snippets.

@jordanorelli
Created June 14, 2011 18:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanorelli/1025525 to your computer and use it in GitHub Desktop.
Save jordanorelli/1025525 to your computer and use it in GitHub Desktop.
Execute raw database queries from file in a Django project
#!/usr/bin/env python
# Load the Django environment
from django.core.management import setup_environ
import os
import sys
try:
project_path = os.environ['DJANGO_PROJECT_PATH']
except KeyError:
raise Exception("Unable to locate Django project. Set your operating "
"system's DJANGO_PROJECT_PATH environment variable to "
"point to the root of the Django project.")
if project_path not in sys.path:
sys.path.append(project_path)
settings_module = os.environ.get('DJANGO_SETTINGS_MODULE')
if settings_module:
settings = __import__(settings_module)
else:
import settings
setup_environ(settings)
# End Django environment load.
import argparse
from django.db import connection, transaction
parser = argparse.ArgumentParser(description='Executes a raw database script on a Django project.')
parser.add_argument('filenames', action='append', metavar='FILE', type=str,
help='A file name or list of file names of database '
'scripts to be executed.')
args = parser.parse_args()
cursor = connection.cursor()
for filename in args.filenames:
f = open(filename)
response = cursor.execute(f.read())
f.close()
rows = cursor.fetchall()
for row in rows:
print repr(row)
@jordanorelli
Copy link
Author

this is an exceptionally naive implementation of a direct-to-db sql querying for a Django project. This is handy for really quick, one-off things that you want to do in the database that would be easier in the raw than through the Django ORM, but are too cumbersome to write out on the mysql command-line. The output looks like poop.

@jordanorelli
Copy link
Author

oh right. I chmod +x this, add its directory to my PATH, and then just do shit like "query test.sql". Bonus: use nmap <F10> :!query % <CR> in Vim to bind F10 to execute the current sql script in your editor. Makes scratch querying very comfy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment