扩展用户配置文件以包括配置文件模型后,Django抛出UNIQUE Con​​straint Failed错误 [英] After extending User profile to include a Profile model, Django throws UNIQUE Constraint Failed error

查看:77
本文介绍了扩展用户配置文件以包括配置文件模型后,Django抛出UNIQUE Con​​straint Failed错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我扩展了User模型,使其包含具有以下代码的配置文件:

I extended the User model to include a profile with the following code:

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模型:

I also created a LeaveHistory model with a foreign key to the User model with the following code:

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

我遇到的问题是,每当我尝试创建多个相同的离开历史记录时用户名我收到以下错误:

The problem that I am having is that whenever I try to create more than one LeaveHistories with the same username I get the following error:

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模型有关,因为我在另一个项目上尝试过没有扩展用户模型并且可以正常工作的地方。如果您需要任何其他代码段或澄清信息,请告诉我,谢谢。

I know it probably has something to do with extending the User model because I tried it on another project where the User model hadn't been extended and it worked fine. If you need any other code snippets or clarification let me know, thank you.

推荐答案

我从以下方法更改了LeaveHistory模型:

I changed the LeaveHistory model from:

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

至:

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

但是我没有正确应用迁移,这导致我的UNIQUE约束错误。
我一直在运行

but I wasn't applying the migrations correctly which resulted in my UNIQUE Constraint Error. I kept running

python manage.py makemigrations

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

which didn't detect any new changes in my accounts app. The correct way that worked for me was to specify the app name in the makemigrations command,

python manage.py makemigrations [应用名称]

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

which detected the changes and I could then run python manage.py migrate and it succesfully applied the changes to my database.

这篇关于扩展用户配置文件以包括配置文件模型后,Django抛出UNIQUE Con​​straint Failed错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆