您好,我正在使用 sqlite3 数据库开发一个 django python 应用程序。我对在我的 models.py 中定义的 django 用户模型进行了扩展,如下所示:
#Account Model
class Account(models.Model):
user = models.OneToOneField(User)
avatar_url = models.CharField(max_length=200)
profile_url = models.CharField(max_length=200)
account_type = models.CharField(max_length=60, choices=choices.ACCOUNT_TYPE)
我还有一个创建 Account 对象
的方法和一个定义如下的 post_save
处理程序:
#Function to Create user Account/Profile
def create_user_account(sender, instance, created, **kwargs):
if created:
models.Account.objects.create(user=instance)
#Create User / User Registration
def UserRegistration(request):
if request.method == 'POST':
username = request.POST['fn'].capitalize() + ' ' + request.POST['ln'].capitalize()
# CREATE USER
newuser = User.objects.create_user(username=username,
email=request.POST['email'],
password=request.POST['pw'])
newuser.save()
return HttpResponse(username)
#Post Save handler to create user Account/Profile
post_save.connect(create_user_account, sender=User)
现在,每当我尝试注册新用户时,我都会收到以下数据库错误:
DatabaseError at /register/
table engine_account has no column named user_id
Request Method: POST
Request URL: http://localhost:8000/register/
Django Version: 1.4
Exception Type: DatabaseError
Exception Value:
table engine_account has no column named user_id
Exception Location: /usr/local/lib/python2.7/dist-packages/Django-1.4-py2.7.egg/django/db/backends/sqlite3/base.py in execute, line 337
Python Executable: /usr/bin/python
Python Version: 2.7.3
而且我不知道 "user_id"
字段是从哪里来的……有什么想法吗?
附言:
表 engine_account 基本上是名为 Engine
的应用程序中的 Account
类
最佳答案
运行 syncdb 后是否编辑了 models.py?
如果是这样,那么您应该手动编辑您的表或使用以下方法重新创建您的数据库:
python manage.py syncdb
在项目目录中应用更改。
2019 年更新:syncdb
从 Django 1.9 开始不推荐使用。使用
python manage.py makemigrations <app_name>
python manage.py migrate --run-syncdb
2020 年更新:我想在我的回答中添加更多描述。
如果模型和对应的表不匹配就会出现这个问题。这意味着您更改了模型但未迁移更改。有些不明白makemigrations
之间的区别和 migrate
命令。为了更清楚,我将尝试解释差异:
./manage.py makgemigrations <app_name>
:给定应用程序模型的更改将与以前的迁移进行比较。如果没有 app_name
如果所有被跟踪的应用程序都将受到控制,并且如果有任何更改,将创建迁移。每个应用程序都有其迁移目录,此命令将在该目录中创建相关的迁移。创建迁移时,它对数据库没有任何更改,需要应用迁移。如果您不应用迁移,那么您仍然会遇到同样的错误。
./manage.py migrate
:由 makemigrations
创建的迁移命令应用于数据库。在生产环境中迁移时需要小心。
./manage.py showmigrations
:此命令列出迁移的状态,您可以查看是否应用了迁移。通常状态存储在数据库中,但不需要连接到数据库并爬取数据。此命令为您提供明确的输入。
关于python - Django ( python ): DatabaseError : x Table has No Column named y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11175856/