django call_command syncdb失败:无法打开数据库文件

时间:2013-08-02 02:06:50

标签: database django

我想在syncdb之后添加一些python代码,所以我决定编写一个build.py来执行包括syncdb在内的所有操作。

我在build.py中写了一些东西:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from django.core.management import call_command
from django.contrib.auth.models import User
call_command('syncdb', interactive=False)

但是当我跑build.py时,它说:

Traceback (most recent call last):
  File "/home/csimstu/PycharmProjects/TeenHope/TeenHope/build.py", line 5, in <module>
    call_command('syncdb', interactive=False)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 161, in call_command
    return klass.execute(*args, **defaults)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 255, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 385, in handle
    return self.handle_noargs(**options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/syncdb.py", line 56, in handle_noargs
    cursor = connection.cursor()
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 324, in cursor
    cursor = self.make_debug_cursor(self._cursor())
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 306, in _cursor
    self._sqlite_create_connection()
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 296, in _sqlite_create_connection
    self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file

我已经尝试过./manage.py syncdb并在交互式shell模式下使用call_command,两种方式都完美正常。怎么会这样?

1 个答案:

答案 0 :(得分:1)

如果找不到数据库文件,可能是因为您没有在设置中使用完整路径。

import os
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.realpath(os.path.join(os.path.dirname(__file__), "relative_path_here", "database.db")),

超出主题:我建议使用Fabric来实现这种命令。