Python Django:DatabaseError 列不存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4687275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:55:54  来源:igfitidea点击:

Django: DatabaseError column does not exist

pythondatabasedjangomodels

提问by Nick Heiner

I'm having a problem with Django 1.2.4.

我在使用 Django 1.2.4 时遇到问题。

Here is a model:

这是一个模型:

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

Right after flushing the database, I use the shell:

刷新数据库后,我立即使用 shell:

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...

What am I doing wrong here?

我在这里做错了什么?

Update: If I comment out the ForeignKey, the problem disappears.

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

Update 2: Curiously, this unit test works just fine:

更新 2:奇怪的是,这个单元测试工作得很好:

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

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

Why does it work here but not in the shell?

为什么它在这里有效,而在 shell 中无效?

Update 3: The reason it works in unit testing but not the shell may have something to do with the different databases being used:

更新 3:它在单元测试中工作而不是 shell 的原因可能与正在使用的不同数据库有关:

settings.py:

设置.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'
        }
    }

Update 4: Confirmed that when I use SQLite3 as the db, everything works fine.

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

采纳答案by amcashcow

Try completely dropping/wiping the database before running syncdb.

在运行 syncdb 之前尝试完全删除/擦除数据库。

I remember needing to do that a while back when I had made changes to foreign key fields.

我记得在我对外键字段进行更改时需要这样做。

回答by melsk

I faced the same problem and noticed that in the backend database the field which houses foreign keys did not exist. The problem disappeared after I created the field (which I think is peculiar). Django doesn't seem to create field labelled as Foreign key. Any reason why?

我遇到了同样的问题,并注意到在后端数据库中,包含外键的字段不存在。在我创建该字段后问题就消失了(我认为这很奇怪)。Django 似乎没有创建标记为外键的字段。有什么理由吗?

回答by Alex Stewart

I fixed this issue by dropping the specific table to that model of question. Then used:

我通过将特定表删除到该问题模型来解决此问题。然后使用:

python manage.py syncdb

If you use PostgreSQL then i recommend using phppgadmin its a web interface similar to PHPmyadmin that is used for mySQL.

如果您使用 PostgreSQL,那么我建议您使用 phppgadmin,它是一个类似于用于 mySQL 的 PHPmyadmin 的 Web 界面。

Alternative to the user interface you can just do command line

替代用户界面,您可以只执行命令行

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

When in \d, escape by pressing q.

在 \d 中时,按 q 退出。

回答by Ernest Jumbe

if you are using Django 1.8 you should create the column. To make sure you create the column correctly find the migration file in which you created the field and run:

如果您使用的是 Django 1.8,您应该创建该列。要确保正确创建列,请找到您在其中创建字段的迁移文件并运行:

./manage.py sqlmigrate app_name migration_name_sans_extension

This will output the sql commands to create the column. Be sure to include the commands that handle relationships and run the commands in your databse console. You won' have to do anything extreme, like dropping the table or the database.

这将输出用于创建列的 sql 命令。确保包含处理关系的命令并在您的数据库控制台中运行这些命令。您不必做任何极端的事情,例如删除表或数据库。

回答by Ali

Please Read this before you drop your entire DB

请在删除整个数据库之前阅读此内容

I had same issue. Please read the exception completely. I had a ModelForm class that read from my table to build a form and exception was there. I commented out and then run the makemigrations and works completely. After that I commented the ModelForm class and everything is working perfect.

我有同样的问题。请完整阅读异常。我有一个 ModelForm 类,它从我的表中读取以构建一个表单,并且存在异常。我注释掉然后运行 ​​makemigrations 并完全工作。之后,我评论了 ModelForm 类,一切正常。

Hope this helps.

希望这可以帮助。