Krithika Raghavendran
Krithika Raghavendran

Reputation: 457

django - UNIQUE CONSTRAINED FAILED error

This is what my models.py looks like:

   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)

I added customer_id to Customer after I added the same in CustomerDetail as foreign key. Why do I still get this error after running migrate, even after I added unique=True to 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

Upvotes: 1

Views: 798

Answers (1)

cutteeth
cutteeth

Reputation: 2213

It seems like you are already having some objects as per old model definitions. By default django creates a field named as id to every model in database. It can be accesses by modelName.id.

In your case I guess what happened is that you are having some objects in database with customer.id as primary as primary key. So when you changed the models and applied migrations, existing objects are checked and another unique field is tried to added as a primary key. Here the workaround is to delete all the existing objects after removing the customer_id field and then try recreating the field and run migrations.

HTH

Upvotes: 1

Related Questions