对第一次查询django sqlite3数据库的OperationError

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

标签: python django sqlite

settings.py的开头有以下内容。

import os, sys

PROJECT_PATH            = os.path.dirname(os.path.abspath(__file__))
CURRENT_DIR             = os.path.dirname(__file__)
TEMPLATE_DIRS           = (os.path.join(CURRENT_DIR, 'templates'),)
STATICFILES_DIRS        = (os.path.join(CURRENT_DIR, 'static'),)

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
  # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.sqlite3', 
    'NAME': '/home/ubuntu/myapp/myapp',       
  }
}

views.py调用数据库后,我在错误日志中收到以下内容。

[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 372, in count
[time] [error]     return self.query.get_count(using=self.db)
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 423, in get_count
[time] [error]     number = obj.get_aggregation(using=using)[None]
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/query.py", line 389, in get_aggregation
[time] [error]     result = query.get_compiler(using).execute_sql(SINGLE)
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 839, in execute_sql
[time] [error]     cursor = self.connection.cursor()
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/__init__.py", line 324, in cursor
[time] [error]     cursor = self.make_debug_cursor(self._cursor())
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 306, in _cursor
[time] [error]     self._sqlite_create_connection()
[time] [error]   File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 296, in _sqlite_create_connection
[time] [error]     self.connection = Database.connect(**kwargs)
[time] [error] OperationalError: unable to open database file

如何正确引用settings.py中的数据库文件?

2 个答案:

答案 0 :(得分:0)

'NAME': '/home/ubuntu/myapp/myapp'看起来就像你指的是文件夹而不是文件。对于SQLite,数据库名称必须是完整路径,包括文件名,因此,当您以编程方式获得项目文件夹时,可以使用它来构造文件路径:

'NAME': os.path.join(PROJECT_PATH, 'mydb.db')

答案 1 :(得分:0)

您需要运行python manage.py syncdb,因为该流程将创建数据库,然后才能在views.py或其他任何位置访问它。