简体   繁体   中英

python django automated data addition

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.

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 (eg 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", ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM