Why django reports a "missing foreign key error" when creating a record referencing a key just created ?
have a look a this code:
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) )
the doRegister view raises an exception at 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 ».
which can be translated "the key (user_id)=(8) can't be found in table myapp_user"
But the record in User with an id=8 exists
> > User.objects.get(id=8)
<User: tg>
note: also, the id=8 is being recycled here. It has been already given for a previous record that has then been deleted.
Edit
Even django administration can't add a Realm record refering this user. But the strange thing is that it's ok with old records (id=1) which haven't been recycled.
I suspect it might be related to recycling because some people are experiencing similar issues (duplicate keys): http://www.vlent.nl/weblog/2011/05/06/integrityerror-duplicate-key-value-violates-unique-constraint/ or IntegrityError duplicate key value violates unique constraint - django/postgres
I've put more about the table below
Here is the output of the manage.py sql command:
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;
and here's the serialisation of the table from 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
);