2016-02-26 136 views
1

所以我有Django的1.8.9django-filer,我開始運行到這個問題Django的過濾器IntegrityError在/管理/文件管理器/文件夾/

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去除約束並添加新約束看起來並不是最好的方法。

+1

你嘗試'遷移'你的分貝? – ilse2005

+0

是的,我做了遷移和遷移 – psychok7

回答

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會爲你做。

我還在測試,但到目前爲止它的工作沒有更多的錯誤

UPDATE:

我加寫有,因爲這仍然指向錯誤的用戶django_admin_log條目RUNSQL一個datamigration:

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;"), 
] 

將此應用於受影響的數據庫並修復後,請刪除此代碼,以便它可以在新數據庫上運行而不會拋出不存在的異常。