Python Django 模型(1054,“'字段列表'中的未知列”)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3787237/
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
Django Models (1054, "Unknown column in 'field list'")
提问by Srikar Appalaraju
No idea why this error is popping up. Here are the models I created -
不知道为什么会弹出这个错误。这是我创建的模型 -
from django.db import models
from django.contrib.auth.models import User
class Shows(models.Model):
showid= models.CharField(max_length=10, unique=True, db_index=True)
name = models.CharField(max_length=256, db_index=True)
aka = models.CharField(max_length=256, db_index=True)
score = models.FloatField()
class UserShow(models.Model):
user = models.ForeignKey(User)
show = models.ForeignKey(Shows)
Here is the view from which I access these models -
这是我访问这些模型的视图 -
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
def user_page(request, username):
try:
user = User.objects.get(username=username)
except:
raise Http404('Requested user not found.')
shows = user.usershow_set.all()
template = get_template('user_page.html')
variables = Context({
'username': username,
'shows' : shows})
output = template.render(variables)
return HttpResponse(output)
At this point I get an error -
在这一点上我得到一个错误 -
OperationalError: (1054, "Unknown column 'appname_usershow.show_id' in 'field list'")
OperationalError: (1054, “'field list' 中的未知列 'appname_usershow.show_id'”)
As you see this column is not even present in my models? Why this error?
如您所见,我的模型中甚至不存在此列?为什么会出现这个错误?
采纳答案by Srikar Appalaraju
As @inception said my tables schema had changed & running syncdbdid not update already created tables.
正如@inception 所说,我的表架构已更改并且正在运行syncdb并不会更新已创建的表。
Apparently any changes to the models when updated through syncdbdoes not change (as in update/modify) the actual tables. So I dropped the relevant DB & ran syncdbon empty DB. Now it works fine. :)
显然,更新时对模型的任何更改syncdb都不会更改(如更新/修改)实际表。所以我删除了相关的数据库并syncdb在空数据库上运行。现在它工作正常。:)
For others, SOUTHdata migration tool for Django seems to be favorite option. It seems to provide options which django models & syncdbfalls short on. Must check out...
对于其他人来说,用于 Django 的SOUTH数据迁移工具似乎是最喜欢的选择。它似乎提供了 django 模型和syncdb不足的选项。必须检查...
Update 29th Sept 2019: From Django 1.7 upwards, migrations are built into the core of Django. If you are running a previous lower version of Django, you can find the repository on BitBucket.
2019 年 9 月 29 日更新:从 Django 1.7 起,迁移已内置到 Django 的核心中。如果您运行的是以前较低版本的 Django,您可以在BitBucket上找到存储库。
回答by Srikanth Chundi
Normally I get this when when I'm trying to access field which doesn't exist in Database.
通常,当我尝试访问数据库中不存在的字段时,我会得到这个。
Check if the field exist in the database. If you change model and perform syncdb it won't update the database, I'm not sure if that's the case.
检查该字段是否存在于数据库中。如果您更改模型并执行同步数据库,它不会更新数据库,我不确定是否是这种情况。
On other note Django offers shortcut to replace try/except block in your code using get_object_or_404. (available in django.shortcuts )
另一方面,Django 提供了使用 get_object_or_404 替换代码中的 try/except 块的快捷方式。(在 django.shortcuts 中可用)
try:
user = User.objects.get(username=username)
except:
raise Http404('Requested user not found.')
can be changed to:
可以改为:
user = get_object_or_404(User, username=username)
回答by Srikar Appalaraju
maybe your tables schema has been changed? Also, running syncdbdoes not update already created tables.
也许您的表架构已更改?此外,运行syncdb不会更新已创建的表。
You might need to drop all the tables & then run syncdbagain. Also remember to take backup of your data!!
您可能需要删除所有表,然后syncdb再次运行。还记得备份你的数据!!
回答by pravish
I created a model file for my app and then did several sqlallas I refined my tables. One of the changes I made was I set primary_key=Trueto one of my fields. At the end called for syncdb. Added a dummy value and and tried to access it with User.objects.all(), Userbeing my model class. Although this worked fine, this error came up while printing the list returned by the all()call. It read DatabaseError: (1054, "Unknown column 'polls_user.id' in 'field list'")
我为我的应用程序创建了一个模型文件,然后在sqlall改进我的表格时做了几个。我所做的更改primary_key=True之一是我设置了我的领域之一。最后呼吁syncdb。添加了一个虚拟值并尝试使用 访问它User.objects.all(),这User是我的模型类。尽管这工作正常,但在打印all()调用返回的列表时出现此错误。它读DatabaseError: (1054, "Unknown column 'polls_user.id' in 'field list'")
Surprisingly, I tried and could get it resolved with another call to syncdb. I remember not having seen the id column in the table at any time throughout the exercise when I checked it through the mysql command line client.
令人惊讶的是,我尝试并可以通过另一个调用来解决它syncdb。我记得当我通过 mysql 命令行客户端检查它时,在整个练习过程中的任何时候都没有看到表中的 id 列。
回答by Ni Xiaoni
I have met the same problems:
我遇到了同样的问题:
First, run
第一次运行
manage.py sqlall [appname]
and you can find:
你可以找到:
`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY,
and I add the column manual:
我添加了列手册:
ALTER TABLE tb_realtime_data ADD id integer AUTO_INCREMENT NOT NULL PRIMARY KEY FIRST;
and then it worked.
然后它起作用了。
I think django will add the column called id itself.
我认为 django 会添加名为 id 的列本身。
For convenience, each model is given an autoincrementing primary key field named id unless you explicitly specify primary_key=True on a field (see the section titled “AutoField” in Appendix A).
为方便起见,每个模型都有一个名为 id 的自动递增主键字段,除非您在字段上明确指定 primary_key=True(请参阅附录 A 中标题为“AutoField”的部分)。
you can click herefor details.
你可以点击这里了解详情。
Good luck.
祝你好运。
回答by RdB
In the appropriate field explicitly set
在适当的字段中明确设置
primary_key = True
回答by keverly
I received this error while trying to use Django Rest Framework serializers. Make sure if you have a serializer that subclasses ModelSerializer, that you migrate any changes to the Models before writing your serializer classes (or just comment anything related to the serializer, migrate, then uncomment).
我在尝试使用 Django Rest Framework 序列化程序时收到此错误。确保您有一个子类化的序列化器,ModelSerializer在编写序列化器类之前将任何更改迁移到模型(或者只是注释与序列化器相关的任何内容,迁移,然后取消注释)。
回答by misybing
The direct solution is delete files under folder ../Project/App/migrations, and the method to avoid this problem is create new databaes table column instead of chagne the existing one.
直接的解决办法是删除../Project/App/migrations文件夹下的文件,避免这个问题的方法是创建新的数据库表列而不是修改现有的列。
回答by slajma
This is quite an old question but you might find the below useful anyway:
Check the database, you're most likely missing the show_idin the appname_usershowtable.
这是一个相当古老的问题,但无论如何您可能会发现以下有用:检查数据库,您很可能show_id在appname_usershow表中遗漏了。
This could occur when you change or add a field but you forget running migration.
当您更改或添加字段但忘记运行迁移时,可能会发生这种情况。
OR
或者
When you're accessing a non managed table and you're trying to add a ForeignKeyto your model.
Following the example above:
当您访问非托管表并尝试将 a 添加ForeignKey到模型时。按照上面的例子:
class UserShow(models.Model):
# some attributes ...
show = models.ForeignKey(Show, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'appname_departments'
回答by user12250631
PS F:\WebApp> python manage.py makemigrations You are trying to add a non-nullable field 'price' to destination without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option: 2 PS F:\WebApp> python manage.py sqlmigrate travello 0001
PS F:\WebApp> python manage.py makemigrations 您正试图在没有默认值的情况下向目的地添加一个不可为空的字段“价格”;我们不能这样做(数据库需要一些东西来填充现有的行)。请选择一个修复:1)现在提供一次性默认值(将在所有现有行上设置此列的空值)2)退出,让我在 models.py 中添加一个默认值 选择一个选项:2 PS F:\WebApp> python manage.py sqlmigrate travello 0001
BEGIN;
开始;
-- Create model Destination
-- 创建模型目标
CREATE TABLE travello_destination(idinteger AUTO_INCREMENT NOT NULL PRIMARY KEY, namevarchar(100) NOT NULL, imgvarchar(100) NOT NULL, desclongtext NOT NULL, offerbool NOT NULL);
COMMIT;
PS F:\WebApp> python manage.py makemigrations
Migrations for 'travello':
travello\migrations\0002_destination_price.py
- Add field price to destination
PS F:\WebApp> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions, travello
Running migrations:
Applying travello.0002_destination_price... OK
创建表travello_destination(id整数 AUTO_INCREMENT NOT NULL PRIMARY KEY,namevarchar(100) NOT NULL,imgvarchar(100) NOT NULL,desclongtext NOT NULL,offerbool NOT NULL);犯罪; PS F:\WebApp> python manage.py makemigrations Migrations for 'travello': travello\migrations\0002_destination_price.py - 将字段价格添加到目的地 PS F:\WebApp> python manage.py migrate 要执行的操作:应用所有迁移:admin , auth, contenttypes, session, travello 运行迁移:应用 travello.0002_destination_price... 好的

