我在添加现有模型客户端的新副本时遇到了麻烦,如下所示:
class Client(models.Model):
user = models.OneToOneField(User) # Extending default user model
organization = models.CharField(max_length=40)
def __unicode__(self):
return self.user.first_name + " " + self.user.last_name
我输入shell并输入:
from django.contrib.auth.models import User
from mysiteApp.models import Client
user = User.objects.get(pk=2) # User with pk 2 exists
client = Client(user=user, organization="someorg") # copy creates succesfully
但是,我试图保存副本 client.save()
我得到了这个:
>>> client.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 537, in save
force_update=force_update, update_fields=update_fields)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 641, in save_base
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 215, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 1559, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 844, in execute_sql
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/util.py", line 41, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 389, in execute
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 387, in execute
return Database.Cursor.execute(self, query, params)
IntegrityError: mysiteApp_client.cID may not be NULL
问题是我之前在客户端模型中有过像cID这样的字段,它确实没有NULL,但是现在我没有
manage.py sql mysiteApp显示:
BEGIN;
CREATE TABLE "mysiteApp_client" (
"id" integer NOT NULL PRIMARY KEY,
"user_id" integer NOT NULL UNIQUE REFERENCES "auth_user" ("id"),
"organization" varchar(40) NOT NULL
)
;
manage.py syncdb什么都没改变,我该怎么办? 感谢。
答案 0 :(得分:3)
您的数据库仍处于需要cID字段的状态。这是因为syncdb不会改变现有的表。
要解决您的问题,您有三种选择:
a)删除数据库中的Client表(=丢失数据)并再次运行syncdb
b)使用sql ALTER TABLE
命令手动修改数据库
c)使用South(introduction)之类的迁移工具来反映您在数据库中对models.py所做的更改。我建议学习如何处理South,因为一旦你在制作中,你可能需要这样的迁移工具。