2016-12-20 3 views
0

を投げ、私は次のコードを使用してプロファイルを利用できるように、ユーザモデルを拡張しました次のコードでUserモデルに:Profileモデルを利用できるように、ユーザプロファイルを拡張した後、DjangoはUNIQUE制約失敗しましたエラー

class LeaveHistory(models.Model): 
    LEAVE_CHOICES = (
     (True, 'PTO'), #is chargeable? 
     (False, 'Jury Duty'), #is chargeable? 
     (False, 'Voting'), #is chargeable? 
     (False, 'Military Leave'), #is chargeable? 
     (False, 'Bereavement'), #is chargeable? 
     (True, 'Emergency'), #is chargeable? 
    ) 

    user = models.ForeignKey(User, on_delete=models.CASCADE) 
    leave_start_date = models.DateTimeField(auto_now=False, auto_now_add=False) 
    leave_end_date = models.DateTimeField(auto_now=False, auto_now_add=False) 
    leave_type = models.BooleanField(choices=LEAVE_CHOICES) 

    def __str__(self): 
     return self.user.username 

私が午前問題は、私は同じユーザー名で複数のLeaveHistoriesを作成しようとするたびに、私は次のエラーを取得するということです0

IntegrityError at /admin/accounts/leavehistory/add/ 
UNIQUE constraint failed: accounts_leavehistory.user_id 
Request Method: POST 
Request URL: http://localhost:8000/admin/accounts/leavehistory/add/ 
Django Version: 1.10.3 
Exception Type: IntegrityError 
Exception Value:  
UNIQUE constraint failed: accounts_leavehistory.user_id 
Exception Location: C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 337 
Python Executable: C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\python.exe 
Python Version: 3.5.2 
Python Path:  
['C:\\django projects\\company_projects', 
'C:\\Users\\achesley\\AppData\\Local\\Programs\\Python\\Python35-32\\python35.zip', 
'C:\\Users\\achesley\\AppData\\Local\\Programs\\Python\\Python35-32\\DLLs', 
'C:\\Users\\achesley\\AppData\\Local\\Programs\\Python\\Python35-32\\lib', 
'C:\\Users\\achesley\\AppData\\Local\\Programs\\Python\\Python35-32', 
'C:\\Users\\achesley\\AppData\\Local\\Programs\\Python\\Python35-32\\lib\\site-packages'] 
Server time: Tue, 20 Dec 2016 16:03:13 -0700 

Environment: 


Request Method: POST 
Request URL: http://localhost:8000/admin/accounts/leavehistory/add/ 

Django Version: 1.10.3 
Python Version: 3.5.2 
Installed Applications: 
['django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'crispy_forms', 
'accounts'] 
Installed Middleware: 
['django.middleware.security.SecurityMiddleware', 
'django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware'] 



Traceback: 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py" in execute 
    64.     return self.cursor.execute(sql, params) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 
    337.   return Database.Cursor.execute(self, query, params) 

The above exception (UNIQUE constraint failed: accounts_leavehistory.user_id) was the direct cause of the following exception: 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\exception.py" in inner 
    39.    response = get_response(request) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response 
    187.     response = self.process_exception_by_middleware(e, request) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in _get_response 
    185.     response = wrapped_callback(request, *callback_args, **callback_kwargs) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\contrib\admin\options.py" in wrapper 
    544.     return self.admin_site.admin_view(view)(*args, **kwargs) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\decorators.py" in _wrapped_view 
    149.      response = view_func(request, *args, **kwargs) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 
    57.   response = view_func(request, *args, **kwargs) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\contrib\admin\sites.py" in inner 
    211.    return view(request, *args, **kwargs) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\contrib\admin\options.py" in add_view 
    1509.   return self.changeform_view(request, None, form_url, extra_context) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\decorators.py" in _wrapper 
    67.    return bound_func(*args, **kwargs) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\decorators.py" in _wrapped_view 
    149.      response = view_func(request, *args, **kwargs) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\decorators.py" in bound_func 
    63.     return func.__get__(self, type(self))(*args2, **kwargs2) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\contextlib.py" in inner 
    30.     return func(*args, **kwds) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\contrib\admin\options.py" in changeform_view 
    1449.     self.save_model(request, new_object, form, not add) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\contrib\admin\options.py" in save_model 
    1007.   obj.save() 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\base.py" in save 
    796.      force_update=force_update, update_fields=update_fields) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\base.py" in save_base 
    824.    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\base.py" in _save_table 
    908.    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\base.py" in _do_insert 
    947.        using=using, raw=raw) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\manager.py" in manager_method 
    85.     return getattr(self.get_queryset(), name)(*args, **kwargs) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py" in _insert 
    1045.   return query.get_compiler(using=using).execute_sql(return_id) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 
    1054.     cursor.execute(sql, params) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py" in execute 
    79.    return super(CursorDebugWrapper, self).execute(sql, params) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py" in execute 
    64.     return self.cursor.execute(sql, params) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\utils.py" in __exit__ 
    94.     six.reraise(dj_exc_type, dj_exc_value, traceback) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\six.py" in reraise 
    685.    raise value.with_traceback(tb) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py" in execute 
    64.     return self.cursor.execute(sql, params) 

File "C:\Users\achesley\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 
    337.   return Database.Cursor.execute(self, query, params) 

Exception Type: IntegrityError at /admin/accounts/leavehistory/add/ 
Exception Value: UNIQUE constraint failed: accounts_leavehistory.user_id 

Userモデルが拡張されておらず、正常に動作していた別のプロジェクトでこのモデルを試したので、おそらくUserモデルの拡張と関係があることは知っています。他のコードスニペットや説明が必要な場合は、教えてください。ありがとうございます。

+0

'makemigrations'と' migrate'を実行しましたか? – Selcuk

+1

エラーがモデルと一致しません。助けが必要な場合は、正確なエラー・トレースを投稿してください。 – e4c5

+0

@selcuk問題を解決しなかったmakemigrationsとmigrateを実行しました。私はその後、データベースをフラッシュして最初から始めましたが、それでも動作しませんでした。 – FlashBanistan

答えて

0

私はからLeaveHistoryモデルを変更:に

user = models.OneToOneField(User, on_delete=models.CASCADE) 

user = models.ForeignKey(User, on_delete=models.CASCADE) 

が、私は私のUNIQUE制約エラーが生じ正しくマイグレーションを適用していませんでした。 私は私のアプリをアカウント内のすべての新しい変更を検出しなかった

のpython manage.pyのmakemigrations

を走り続けました。私のために働いた正しい方法はmakemigrationsコマンドでアプリ名を指定した、

変化を検出して、私はその後、のpython管理を実行する可能性のpython manage.pyのmakemigrations [アプリ名]

.pyマイグレーションと私のデータベースに変更を適用しました。

-2

これは、外部キーを使用してLeaveHistoryをUserモデルにリンクするためです。代わりに、プロファイルモデルにリンクする必要があります。

class LeaveHistory(models.Model): 
    ... 
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE) 
+0

そして、とにかく 'Profile'と' User'はOneToOne関係でリンクしています。 – Selcuk

+0

ユーザーは抽象的な方法で使用されるため、アプリケーション固有のものにはリンクされません。そのため、「中型人」として使用できるようにプロファイルモデルを作成します。 ユーザモデルはDjangoの認証システムではデフォルトであり、関連するテーブルでは外部キーが一意でなければならないため、制約されていると思います。したがって、あなたの場合、LeaveHistoryインスタンスへのUser参照は1つしかなく、同じユーザーで別のUser参照を作成することはできません。 私はこの問題がプロファイルで発生するとは思わない。 – zubhav

+1

これは純粋な推測であり、質問の問題とは関係ありません。 'User'は抽象モデルではなく、子モデルがそうであると定義されていない限り、別のモデル**の外来キー**を一意にすることはできません。 OPはおそらく 'user' fkを一意にするか、1対1のフィールドとして定義しましたが、データベーススキーマを移行するのを忘れてしまいました。 – Selcuk

関連する問題