如何解决django unique constraint的奇怪异常

How to solve the strange exception of django unique constraint

这是我的 models.py 的样子:

class Project(models.Model):
    name = models.CharField(max_length="40", unique=True)

class Entry(models.Model):
    project = models.ForeignKey(Project)
    name = models.CharField(max_length="40",unique=False)

当我想创建一个新条目时 我会使用 ajax 到 post 服务器条目的名称

createEntry 负责处理 ajax post 请求

def createEntry(request):     
    if request.method == 'POST':   
        response_data = {}    
        name = request.POST.get('name')
        projectId = request.session['projectId'] 
        try:
            project = Project.objects.get(pk=projectId)
            entry=Entry(name=name)         
            project.entry_set.add(entry)   
        except:
            print traceback.format_exc()   
            return HttpResponseBadRequest("Failed")
    response_data['result'] = 'Create post successful!'

    return JsonResponse(response_data)

除了在创建与现有条目同名的新条目时发生异常外,一切顺利

这是回溯信息

Traceback (most recent call last):
  File "/home/vagrant/src/src/views.py", line 70, in createEntry
    project.entry_set.add(entry)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 708, in add
    obj.save()
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 589, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 617, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 698, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 731, in _do_insert
    using=using, raw=raw)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 92, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 921, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py", line 920, in execute_sql
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 81, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 485, in execute
    return Database.Cursor.execute(self, query, params)
IntegrityError: UNIQUE constraint failed: src_entry.name

这是我的问题:

既然我明确定义了Entry的name字段为unique=False,那么name字段不应该有唯一性约束,那怎么会出现这个异常呢?

数据库正在强制执行此 UNIQUE 约束。您将需要 运行 迁移以移除限制。

检查数据库迁移是否有问题。 如果您使用的是 django 数据库内置的数据库 postgresql 或 sqlite 之一,则可以执行以下操作。

1.sqlite:- 只需删除 django 框架中的 sqlite 数据库容器并执行以下操作

$python manage.py makemigrations
$python manage.py migrate
$python manage.py runserver

2.postgresql :- 您需要按照以下步骤删除数据库

$sudo -u postgres psql
postgresql#drop database YOUR_DATABASE_NAME
postgresql#create database NEW_DATABASE_NAME
postgresql#grant all privileges on database "NEW_DATABASE_NAME" to YOUR_USER_NAME

$python manage.py makemigrations
$python manage.py migrate
$python manage.py createsuperuser
$python manage.py runserver