1

所以我有 django1.8.9并且django-filer我开始遇到这个问题

insert or update on table "filer_clipboard" violates foreign key constraint "filer_clipboard_user_id_2b30c76f2cd235df_fk_auth_user_id"
DETAIL:  Key (user_id)=(67) is not present in table "auth_user".

我意识到这与我添加的新自定义用户有关,但查看我看到的文件管理器源代码也应该处理它

class Clipboard(models.Model):
    user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL', 'auth.User'), verbose_name=_('user'), related_name="filer_clipboards")

我有AUTH_USER_MODEL = 'authtools.User'所以它仍然没有意义所以我查看了数据库,我发现我的旧约束仍然存在(它没有更新到我的新用户)

postgres=# \d filer_clipboard
                          Table "public.filer_clipboard"
 Column  |  Type   |                          Modifiers                           
---------+---------+--------------------------------------------------------------
 id      | integer | not null default nextval('filer_clipboard_id_seq'::regclass)
 user_id | integer | not null
Indexes:
    "filer_clipboard_pkey" PRIMARY KEY, btree (id)
    "filer_clipboard_e8701ad4" btree (user_id)
Foreign-key constraints:
    "filer_clipboard_user_id_2b30c76f2cd235df_fk_auth_user_id" FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED
Referenced by:
    TABLE "filer_clipboarditem" CONSTRAINT "filer_clipb_clipboard_id_335d159e1aea2cdc_fk_filer_clipboard_id" FOREIGN KEY (clipboard_id) REFERENCES filer_clipboard(id) DEFERRABLE INITIALLY DEFERRED

关于如何解决这个问题的任何想法?诉诸 SQL 来消除约束并添加新约束似乎不是最好的方法。

4

1 回答 1

0

在文件管理器代码库中设置db_constraint=False所有用户外键,应用迁移然后再次将其删除或将其设置为db_constraint=True(因为有影响https://docs.djangoproject.com/en/1.8/ref/models/fields/#django .db.models.ForeignKey.db_constraint)自动创建我需要的新约束。

这比手动编写 sql 要好得多,因为 django 会为您完成。

我仍在测试,但到目前为止它的工作没有更多错误

更新:

我添加了使用 RUNSQL 编写数据迁移,因为 django_admin_log 条目仍然指向错误的用户:

operations = [
    migrations.RunSQL("BEGIN;"),
    migrations.RunSQL(
        "ALTER TABLE django_admin_log DROP CONSTRAINT "
        "django_admin_log_user_id_52fdd58701c5f563_fk_auth_user_id"
    ),
    migrations.RunSQL(
        "ALTER TABLE django_admin_log ADD CONSTRAINT "
        "django_admin_log_user_id_52fdd58701c5f563_fk_authtools_user_id "
        "foreign key (user_id) references authtools_user(id) "
        "DEFERRABLE INITIALLY DEFERRED"
    ),
    migrations.RunSQL("COMMIT;"),
]

将此应用到受影响的数据库并修复后,删除此代码,以便它可以在新数据库上运行而不会引发不存在异常。

于 2016-02-26T19:26:03.730 回答