Django(Python):DatabaseError:x表没有名为y的列
您好,我正在使用sqlite3数据库开发django python应用程序。我对mymodels.py中定义的django用户模型进行了如下扩展:Django(Python):DatabaseError:x表没有名为y的列,python,database,django,sqlite,Python,Database,Django,Sqlite,您好,我正在使用sqlite3数据库开发django python应用程序。我对mymodels.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 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)
我还有一个方法来创建帐户对象
和一个post\u 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\u id”
字段是从哪里来的。。有什么想法吗
附言:
表engine\u account基本上是名为
engine
的应用程序中的account
类。运行syncdb后是否编辑了models.py
如果是,则应手动编辑表或使用以下工具重新创建数据库:
python manage.py syncdb
在项目目录中应用更改
2019年更新:
syncdb
在Django 1.9以后的版本中不推荐使用。使用
python manage.py makemigrations
python manage.py migrate--运行syncdb
更新2020:我想在我的答案中添加更多描述 如果模型和相应的表不匹配,则会出现此问题。这意味着您已更改了模型,但未迁移更改。有些命令在
makemigrations
和migrate
命令之间没有区别。为了更清楚地说明这一点,我将尝试解释其中的区别:
/manage.py makgemigrations
:给定应用程序型号上的更改将与以前的迁移进行比较。如果未提供app\u name
,则将控制所有跟踪的应用程序,如果有任何更改,则将创建迁移。每个应用程序都有其迁移目录,此命令将在此目录中创建相关迁移。创建迁移时,数据库上没有任何更改,需要应用迁移。如果不应用迁移,仍然会出现相同的错误
/manage.py migrate
:通过makemigrations
命令创建的迁移应用于数据库。在生产环境上进行迁移时,需要小心
/manage.py showmigrations
:此命令列出迁移的状态,您可以查看是否应用了迁移。通常情况下,状态存储在数据库中,但不需要连接到数据库并对数据进行爬网。此命令为您提供了清晰的输入。syncdb
在django 1.9及更高版本中不推荐使用。因此,对于django 1.9版或更高版本,运行python manage.py makemigrations
,然后运行python manage.py migrate
,我尝试了python manage.py syncdb
,这还不够,因此解决方案是:
我删除了迁移文件
和
我删除了db.sqlite3
文件
我执行了python manage.py makemigrations
和python manage.py migrate
宾果
你忘了运行
syncdb
?@BurhanKhalid谢谢,我太蠢了,但是它仍然给我一个整数错误“列用户名不是唯一的”。。当我的帐户模型中没有定义任何名为“username”的文件时。