Django模型(1054,“字段列表中的未知列”)
我也不知道为什么会出现这个错误。以下是我创建的模型 -
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)
这是我用来访问这些模型的视图 -
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)
在这个时候我遇到了一个错误 -
操作错误: (1054, "字段列表中未知列 'appname_usershow.show_id'")
你看,这个列在我的模型里根本不存在?为什么会出现这个错误呢?
14 个回答
6
通常,我在尝试访问数据库中不存在的字段时会遇到这个问题。
你可以检查一下这个字段在数据库中是否存在。如果你修改了模型并执行了syncdb,它不会自动更新数据库,我不确定是否就是这个情况。
另外,Django提供了一个快捷方式,可以用来替代你代码中的try/except块,叫做get_object_or_404。(在django.shortcuts中可以找到)
try:
user = User.objects.get(username=username)
except:
raise Http404('Requested user not found.')
可以改成:
user = get_object_or_404(User, username=username)
28
可能你的数据库表的结构已经改变了?另外,运行 syncdb
并不会更新已经创建的表。
你可能需要先删除所有的表,然后再运行 syncdb
。还有,记得备份你的数据哦!!
16
正如@inception所说,我的数据库表结构发生了变化,而运行 syncdb
并没有更新已经创建的表。
显然,通过 syncdb
更新模型时,并不会实际修改(也就是更新)数据库中的表。所以我删除了相关的数据库,然后在一个空的数据库上运行了 syncdb
。现在一切正常了。:)
对于其他人来说,SOUTH 这个数据迁移工具在Django中似乎是个热门选择。它提供了一些 syncdb
无法做到的功能,值得一试……
更新 2019年9月29日:从Django 1.7版本开始,迁移功能已经内置在Django的核心中了。如果你使用的是更早的Django版本,可以在 BitBucket 上找到相关的代码库。