我需要导入什么才能访问我的模型?
我想运行一个脚本来填充我的数据库,并且我想通过Django的数据库接口来访问它。
唯一的问题是,我不知道需要导入什么才能访问这个接口。
我该怎么做呢?
5 个回答
5
如果你在项目目录下使用 manage.py
脚本时加上 shell
参数,就不需要手动导入设置了:
$ 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 *
>>>
如果你不需要交互式使用,可以创建一个自定义命令,然后用 manage.py
来运行它。
6
这是我在一个数据加载脚本开头写的内容。
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
这些内容应该在你脚本中做其他事情之前先执行。
另一种方法是使用“fixtures”和“manage.py”。不过如果你只是想一次性加载大量数据来初始化数据库,这种方法应该没问题。
另外,根据你的具体操作,你可能想要或者不想要把所有操作放在一个事务中。如果想要的话,可以取消上面事务那一行的注释,然后把你的代码结构调整得像这样。
transaction.enter_transaction_management()
try:
#Do some stuff
transaction.commit()
finally:
transaction.rollback()
pass
transaction.leave_transaction_management()
13
也要导入你的设置模块
import os
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"
from mysite.polls.models import Poll, Choice
这样就可以解决问题了。