views:

34

answers:

1

I have a script which reads data from a csv file. I need to store the data into a database which has already been created as

$ python manage.py syncdb

so, that automated data entry is possible in an easier manner, as available in the django shell.

A: 

You have to set up a django environment to use in your script, afterwards your python script can work with django models just as in the 'real' site:

The easiest way to do this: set the DJANGO_SETTINGS_MODULE environment variable (e.g. export DJANGO_SETTINGS_MODULE=mysite.settings ). Then your script can do things like:

from app.models import MyModel

a = MyModel(field=value)
a.save()

There are also some other ways, where you have to write some additional code in your script, I prefer these because they do not require an environment variable:

1) setup_environ:

from django.core.management import setup_environ
import mysite.settings
setup_environ(mysite.settings)

2) Create settings on the flow:

from django.conf import settings
settings.configure(DEBUG=False, DATABASE_NAME="mydb", ...)
KillianDS