django - UNIQUE CONSTRAINED FAILED错误

时间:2016-08-23 09:01:04

标签: django primary-key unique-key

这就是我的models.py看起来的样子:

   from django.db import models
   from django.core.validators import RegexValidator

    # Create your models here.
    class Customer(models.Model):
        customer_id = models.AutoField(primary_key=True,unique=True)
        full_name = models.CharField(max_length=50)
        user_email = models.EmailField(max_length=50)
        user_pass = models.CharField(max_length=30)

        def __str__(self):
            return "%s" % self.full_name

    class CustomerDetail(models.Model):
        phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778")
        date_regex = RegexValidator(regex = r'\d{2}[-/]\d{2}[-/]\d{2}', message = "Invalid format! E.g. 05/16/91")

        address = models.CharField(max_length=100)
        date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True)
        company = models.CharField(max_length=30)
        home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
        work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
        customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE)

我在customer_id中添加Customer作为外键后添加CustomerDetail。为什么在运行迁移后仍然会出现此错误,即使我已将unique=True添加到customer_id?

Error:
      Rendering model states... DONE
      Applying newuser.0003_auto_20160823_0128...Traceback (most recent call last):
          File "/home/krag91/Documents/djangodev/virtualenv    /lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in     execute
  return self.cursor.execute(sql, params)
          File "/home/krag91/Documents/djangodev/virtualenv    /lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
  return Database.Cursor.execute(self, query, params)
      sqlite3.IntegrityError: UNIQUE constraint failed:     newuser_customer.customer_id
The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute()
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute
    output = self.handle(*args, **options)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 202, in handle
    targets, plan, fake=fake, fake_initial=fake_initial
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 97, in migrate
    state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 132, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 237, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
    field,
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 231, in add_field
    self._remake_table(model, create_fields=[field])
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 199, in _remake_table
    self.quote_name(model._meta.db_table),
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 112, in execute
    cursor.execute(sql, params)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: newuser_customer.customer_id

1 个答案:

答案 0 :(得分:1)

好像你是already having some objects as per old model definitionsBy default django creates a field named as id to every model in database。它可以通过modelName.id访问。

在你的情况下,我猜想发生的事情是你在数据库中有一些对象,customer.id作为主键。因此,当您更改模型并应用迁移时,existing objects are checked and another unique field is tried to added as a primary key。解决方法是在删除customer_id字段后删除所有现有对象,然后尝试重新创建字段并运行迁移。

HTH