tags:

views:

567

answers:

4

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 to import to gain access to this.

How can this be achieved?

A: 

In addition to your own models files, you need to import your settings module as well.

Lou Franco
+10  A: 

Import your settings module too

import os
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"

from mysite.polls.models import Poll, Choice

should do the trick.

kender
+5  A: 

If you use the shell argument to the manage.py script in your project directory, you don't have to import the settings manually:

$ cd mysite/
$ ./manage.py shell
Python 2.5.2 (r252:60911, Jun 10 2008, 10:35:34) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from myapp.models import *
>>>

For non-interactive use you could implement a custom command and run it with manage.py.

hop
Unless I am missing something, manage.py does not have a runscript subcommand in Django 1.0 If you are using a custom app to provide this functionality you should mention it.
Andre Miller
+4  A: 

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()
Sam Corder
+1, when running in the root of my project, the accepted answer above doesn't work, but your's does!
pufferfish
Shouldn't the line "sys.exit(1)" be indented?
Peter Mortensen