在扩展用户配置文件以包含配置文件模型后,Django抛出UNIQUE Con​​straint Failed错误

时间:2016-12-20 23:55:35

标签: python django django-models

我扩展了用户模型以包含具有以下代码的配置文件:

class Profile(models.Model):
    PTO_TIER_CHOICES = (
        (200.0, 'Boss 5-10 Years'),
        (160.0, 'Boss 2-5 Years'),
        (120.0, 'Boss 0-2 Years'),
        (160.0, 'Peon 5-10 Years'),
        (120.0, 'Peon 2-5 Years'),
        (90.0, 'Peon 0-2 Years'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    pto_tier = models.FloatField(choices=PTO_TIER_CHOICES, default=90.0)

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

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

我还使用以下代码创建了带有用户模型外键的LeaveHistory模型:

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时,我都会收到以下错误:

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模型的项目上尝试过它并且它工作正常。如果您需要任何其他代码片段或说明,请告诉我,谢谢。

2 个答案:

答案 0 :(得分:0)

我改变了LeaveHistory模型:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

Z = np.loadtxt('data.txt')
X = np.linspace(0,3,301)
Y = np.linspace(0,3,301)
X = np.array([X,]*(301)).transpose()
Y = np.array([Y,]*(301))
fig = plt.figure(figsize=(15,15), dpi=100)
ax = fig.add_subplot(2, 1, 1, projection='3d')
plt.hold(True)
ax.view_init(40,300)
surf = ax.plot_surface(X, Y, Z, cmap='jet', rstride=1, cstride=1, antialiased=False, shade=False, alpha=1.0, linewidth=0, vmin=0.25, vmax=0.35);

ax.invert_yaxis()
ax.dist = 11

ax = fig.add_subplot(2, 1, 2)
plt.hold(True)
plt.imshow(Z, cmap='jet', vmin=0.25, vmax=0.35, origin='lower');

plt.show()

为:

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

但我没有正确应用迁移导致我的UNIQUE约束错误。 我一直在跑

python manage.py makemigrations

我的帐户应用中未检测到任何新的更改。对我有用的正确方法是在makemigrations命令中指定应用程序名称,

python manage.py makemigrations [app name]

检测到更改,然后我可以运行 python manage.py migrate ,并成功将更改应用到我的数据库。

答案 1 :(得分:-2)

这是因为您通过外键将LeaveHistory链接到User模型。相反,您应该链接到配置文件模型。

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