I\'d like to run a script to populate my database. I\'d like to access it through the Django database API.
The only problem is that I don\'t know what I would need t
This is what I have at the top of one my data loading scripts.
import string
import sys
try:
import settings # Assumed to be in the same directory.
#settings.DISABLE_TRANSACTION_MANAGEMENT = True
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
#Setup the django environment with the settings module.
import django
import django.core.management
django.core.management.setup_environ(settings)
from django.db import transaction
This should all execute before you do much else in your script.
Another method is to use fixtures and manage.py. Though if you are just trying to accomplish a bulk data load to initialize a database this should work fine.
Also depending on what you are doing you may or may not want to do it all in one transaction. Uncomment the transaction line above and structure your code similar to this.
transaction.enter_transaction_management()
try:
#Do some stuff
transaction.commit()
finally:
transaction.rollback()
pass
transaction.leave_transaction_management()