Django:数据库错误,列不存在

8 投票
5 回答
22809 浏览
提问于 2025-04-16 09:56

我在使用Django 1.2.4的时候遇到了一个问题。

这里有一个模型:

class Foo(models.Model):
    # ...
    ftw = models.CharField(blank=True)
    bar = models.ForeignKey(Bar, blank=True)

在我清空数据库之后,我使用了命令行:

Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) 
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apps.foo.models import Foo
>>> Foo.objects.all()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 67, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 82, in __len__
    self._result_cache.extend(list(self._iter))
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 271, in iterator
    for row in compiler.results_iter():
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 677, in results_iter
    for rows in self.execute_sql(MULTI):
  File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py", line 732, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py", line 15, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
    return self.cursor.execute(query, args)
DatabaseError: column foo_foo.bar_id does not exist
LINE 1: ...t_omg", "foo_foo"."ftw", "foo_foo...

我到底哪里做错了呢?

更新:如果我把ForeignKey注释掉,问题就消失了。

更新 2:有趣的是,这个单元测试运行得很好:

def test_foo(self):
    f = Foo()
    f.save()

    self.assertTrue(f in Foo.objects.all())

为什么在这里可以正常工作,但在命令行里却不行呢?

更新 3:它在单元测试中能正常工作,但在命令行中不行,可能和使用的数据库不同有关:

settings.py

DATABASES = {
    'default': {
        'ENGINE': 'postgresql_psycopg2',
        'NAME': 'foo',
        'USER': 'bar',
        'PASSWORD': 'baz',
        'HOST': '',
        'PORT': '',
    }
}

import sys
if 'test' in sys.argv or True:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'testdb'
        }
    }

更新 4:确认当我使用SQLite3作为数据库时,一切都正常。

5 个回答

3

我解决这个问题的方法是删除了和这个问题相关的特定表。然后我使用了:

python manage.py syncdb

如果你使用的是PostgreSQL数据库,我推荐使用phppgadmin,这个工具是一个网页界面,跟用于mySQL的PHPmyadmin很像。

除了用图形界面,你也可以直接在命令行里操作。

su postgres #change user to postgres
psql <datebase> #access shell for <datebase> database
\d #list all tables
DROP TABLE "" CASCADE #select a table to drop
\q #exit shell

在使用 \d 命令时,如果想退出,可以按 q 键。

5

在你删除整个数据库之前,请先看看这个

我也遇到过同样的问题。请仔细阅读错误信息。我有一个 ModelForm 类,它是从我的表中读取数据来生成表单的,错误就是在这里出现的。我把这部分代码注释掉,然后运行了 makemigrations,结果一切正常。之后我又把 ModelForm 类注释掉,现在一切都运作得很好。

希望这对你有帮助。

9

在运行syncdb之前,试着完全删除或清空数据库。

我记得之前在修改了外键字段的时候,也需要这么做。

撰写回答