为什么django在创建引用刚创建的密钥的记录时会报告“缺少外键错误”?
查看此代码:
def doRegister(request,username, email, password):
user = User.objects.create_user( username, email, password )
realm = createWhereAvailable( user )
realm.save()
return redirect('index')
def createWhereAvailable( user ):
#some logic here... note: Realm extends django's Model
return Realm( x=x, y=y, user=user, name=generateRandomRealmName(x, y) )
doRegister视图在realm.save()中引发异常:
IntegrityError at /myapp/doregister
ERREUR: une instruction insert ou update sur la table « myapp_realm » viole la contrainte de clé
étrangère « user_id_refs_id_9302d6bb »
DETAIL: La clé (user_id)=(8) n'est pas présente dans la table « myapp_user ».
可以翻译"the key (user_id)=(8) can't be found in table myapp_user"
但是具有id = 8的User中的记录存在
> > User.objects.get(id=8)
<User: tg>
注意:此外,id = 8正在此处回收。之前的记录已被删除。
修改
即使是django管理也无法添加引用该用户的Realm记录。但奇怪的是旧的记录(id = 1)没有被回收利用。
我怀疑它可能与回收有关,因为有些人遇到了类似问题(重复密钥):http://www.vlent.nl/weblog/2011/05/06/integrityerror-duplicate-key-value-violates-unique-constraint/或IntegrityError duplicate key value violates unique constraint - django/postgres
我对下表有更多了解
以下是manage.py sql命令的输出:
BEGIN;
CREATE TABLE "myapp_realm" (
"id" serial NOT NULL PRIMARY KEY,
"user_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED,
"name" varchar(30) NOT NULL,
#... some other fields stripped for consision
)
;
COMMIT;
这是pgadmin的表序列化:
CREATE TABLE myapp_realm
(
id serial NOT NULL,
user_id integer NOT NULL,
name character varying(30) NOT NULL,
#... some other fields
CONSTRAINT myapp_realm_pkey PRIMARY KEY (id),
CONSTRAINT user_id_refs_id_9302d6bb FOREIGN KEY (user_id)
REFERENCES myapp_user (id) MATCH Unknown
ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED
)
WITH (
OIDS=FALSE
);