Search code examples
pythondjangodatabaseunique

How to solve the strange exception of django unique constraint


This is what my models.py looks like:

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)

When I want to create a new entry I would use ajax to post the name of the entry to the server

And it's the createEntry which takes care of the ajax post request

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)

Everything goes smoothly right except that when a new entry with a same name of a existing one is being created an exception happens

Here is the traceback info

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

Here goes my question:

Since I have explicitly define the name field of the Entry with unique=False, there shouldn't be unique constraint on the name field, then how could this exception happen?


Solution

  • This UNIQUE constraint is being enforced by the database. You will need to run a migration to remove the constraint.