2

在我更改模型和表单之前,我的 UserProfile 工作正常。我在模型中添加了一个 DateField 并更新了我的 Forms.py 和模板。还做了一个syncdb。

配置文件/models.py

class UserProfiles(models.Model):
    user = models.OneToOneField(User)
    #other fields here
    birthday = models.DateField()

配置文件/forms.py

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfiles
        fields = ('some_field', 'birthday', 'otherfields')

个人资料/views.py

def editprofile(request):
    return render_to_response('profile_edit.html', {'form':UserProfileForm()}, context_instance=RequestContext(request))

这是它抛出的错误。

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "E:\django-sample\proschools\..\proschools\profile\views.py" in generateprofile
  12.             userprofile = UserProfiles.objects.get(user=request.user)
File "C:\Python27\lib\site-packages\django\db\models\manager.py" in get
  132.         return self.get_query_set().get(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in get
  344.         num = len(clone)
File "C:\Python27\lib\site-packages\django\db\models\query.py" in __len__
  82.                 self._result_cache = list(self.iterator())
File "C:\Python27\lib\site-packages\django\db\models\query.py" in iterator
  273.         for row in compiler.results_iter():
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in results_iter
  680.         for rows in self.execute_sql(MULTI):
File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql
  735.         cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\util.py" in execute
  34.             return self.cursor.execute(sql, params)
File "C:\Python27\lib\site-packages\django\db\backends\mysql\base.py" in execute
  86.             return self.cursor.execute(query, args)
File "C:\Python27\lib\site-packages\MySQLdb\cursors.py" in execute
  174.             self.errorhandler(self, exc, value)
File "C:\Python27\lib\site-packages\MySQLdb\connections.py" in defaulterrorhandler
  36.     raise errorclass, errorvalue

Exception Type: OperationalError at /profile/
Exception Value: (1054, "Unknown column 'profile_userprofiles.birthday' in 'field list'")
4

3 回答 3

2

如果表在您添加新列之前存在,syncdb则不会向其中添加新列!syncdb 不改变现有表。考虑使用Django south或手动添加列。

于 2012-04-12T17:29:11.847 回答
2
http://code.google.com/p/django-evolution/

当您运行 ./manage.py syncdb 时,Django 将查找已定义的任何新模型,并添加一个数据库表来表示这些新模型。但是,如果您对现有模型进行更改,./manage.py syncdb 不会对数据库进行任何更改。

这就是 Django Evolution 适合的地方。Django Evolution 是 Django 的一个扩展,它允许您跟踪模型随时间的变化,并更新数据库以反映这些变化。

于 2012-04-13T06:07:57.000 回答
1

Syncdb 不会自动为您创建新字段。您必须完全删除表并运行 syncdb 才能将架构更改应用到数据库。

大多数 django 开发人员使用名为south的第三方应用程序来处理这些类型的迁移。South 将允许您添加字段并迁移数据库,而无需重新创建或手动更改数据库。

于 2012-04-12T17:30:23.503 回答