Django IntegrityError:唯一约束失败

时间:2019-02-25 08:20:08

标签: python django-models

我已经创建了表格。现在,我必须向每个字段添加唯一性约束,但是当我尝试运行 python manage.py migration 时遇到此错误

完整性错误:UNIQUE约束失败:employee.econtact

这是我的代码:-

model.py

from __future__ import unicode_literals
from django.db import models
from django.db import IntegrityError

from django.db import migrations, connection


class Employee(models.Model):
    eid = models.CharField(max_length=20)
    ename = models.CharField(max_length=50)
    email = models.EmailField(default = None, blank =True, null=True)
    econtact = models.IntegerField( null = True, default=None)

    class Meta:
        db_table = "employee"





def alter_table(apps, schema_editor):
    query ="ALTER TABLE <your table> ADD UNIQUE (unique_col);"
    cursor = connection.cursor()
    cursor.execute(query)
    cursor.close()

class Migration(migrations.Migration):

    dependencies = [
        ('app', 'yourlastmigration'),
    ]

    operations = [
        migrations.RunPython(alter_table),
    ]
}

0 个答案:

没有答案