我正在尝试将数据填充到我的数据库中,并且我想使用 django API 来执行此操作。我编写了一个 python 模块,可以很容易地做到这一点。
但是,在 django shell (manage.py) 中,似乎无法运行我的“populate.py”文件。
是否可以从 django shell 运行我的 populate.py?或者,我应该改为运行常规 python 终端并导入必要的 django 组件吗?无论哪种方式,我都会非常感谢一些指示。
您也可以考虑使用loaddata 命令或创建自己的命令
这是我从命令行运行 django 东西的标准包装器。如果您有要运行的 cron 脚本,这也很有用。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys
# If this script lives in a child directory of the main project directory
# uncomment the following 2 lines:
#dir_parent = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
#sys.path.insert(0, dir_parent)
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.db import transaction
# import whatever you like from app.models or whatever
# do random stuff.
# If you are *changing* database records,
# wrap your database code either in:
@transaction.commit_manually
def foo():
... stuff
transaction.commit()
# OR end you script with:
transaction.commit_unless_managed()
更新评论:
上面提到的变量不是file
,它是__file__
(即2个下划线file
和2个下划线)。这总是由 Python 解释器设置为它出现的文件的完整路径。正如评论所说,如果这个脚本位于主目录的子目录中,则文件名的目录为您提供主项目目录的目录名称,并将其添加到sys.path
将确保您的所有导入正常工作。如果脚本位于主目录中并且您从那里执行它,那么您不需要这样做。
试试 django-extensions,它有一个 runscript 命令,你把它放在脚本目录中。
奇怪的是,主文档中似乎缺少该命令,但是如果您 google django-extensions runscript,您会找到示例和文档。