end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

django for python で、table "django_admin_log" violates foreign key エラー

IntegrityError at /admin/diary/diary/add/
insert or update on table "django_admin_log" violates
foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id"
DETAIL:  Key (user_id)=(2) is not present in table "auth_user".

のようなエラーが発生。

https://stackoverflow.com/questions/15124523/integrity-error-on-django-admin-log-after-updating-existing-site-to-new-django-1?rq=1

migrate の漏れ? のような気もしますが、上記urlの通り、 drop table django_admin_log; と、改めての create table 等で解消。

まず、drop table。

sql> DROP TABLE django_admin_log;

次に、以下の sqlmigrate コマンドでsqlが標準出力されるので これを、sqlにて発行。

$ ./manage.py sqlmigrate admin 0001
CREATE TABLE "django_admin_log" (
  "id"          serial NOT NULL PRIMARY KEY,
  "action_time" timestamp with time zone NOT NULL,
  "object_id"   text NULL,
  "object_repr" varchar(200) NOT NULL,
  "action_flag" smallint NOT NULL CHECK ("action_flag" >= 0),
  "change_message" text NOT NULL,
  "content_type_id" integer NULL, "user_id" integer NOT NULL
);
ALTER TABLE "django_admin_log"
  ADD CONSTRAINT "django_admin_log_content_type_id_c4bce8eb_fk_django_co"
  FOREIGN KEY ("content_type_id")
  REFERENCES "django_content_type" ("id")
  DEFERRABLE INITIALLY DEFERRED;
  
ALTER TABLE "django_admin_log"
  ADD CONSTRAINT "django_admin_log_user_id_c564eba6_fk_accounts_customuser_id"
  FOREIGN KEY ("user_id")
  REFERENCES "accounts_customuser" ("id")
  DEFERRABLE INITIALLY DEFERRED;

CREATE INDEX "django_admin_log_content_type_id_c4bce8eb"
  ON "django_admin_log" ("content_type_id");
CREATE INDEX "django_admin_log_user_id_c564eba6"
  ON "django_admin_log" ("user_id");