I'm setting up a django model to store regions, like USA, Germany, etc. I made the region name unique for the table. I have a script that populates the database from a list and if there is a duplicate region name IntegrityError is thrown as expected but then another error happens and I can't tell why from the error message. Any ideas? Thanks!
django.db.utils.DatabaseError: current transaction is aborted, commands ignored until end of transaction block
Model:
class Region(models.Model):
name = models.CharField(max_length=512, unique=True)
def __unicode__(self):
return self.name
Populate code:
try:
Region(name=server['locale']).save()
print 'Added region: %(locale)s' % server
except IntegrityError:
pass
I've confirmed that the IntegrityError is occuring but then I get this error which I dont expect:
File "/home/daedalus/webapps/wowstatus/lib/python2.6/django/db/models/base.py", line 456, in save
self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/home/daedalus/webapps/wowstatus/lib/python2.6/django/db/models/base.py", line 549, in save_base
result = manager._insert(values, return_id=update_pk, using=using)
File "/home/daedalus/webapps/wowstatus/lib/python2.6/django/db/models/manager.py", line 195, in _insert
return insert_query(self.model, values, **kwargs)
File "/home/daedalus/webapps/wowstatus/lib/python2.6/django/db/models/query.py", line 1518, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/daedalus/webapps/wowstatus/lib/python2.6/django/db/models/sql/compiler.py", line 788, in execute_sql
cursor = super(SQLInsertCompiler, self).execute_sql(None)
File "/home/daedalus/webapps/wowstatus/lib/python2.6/django/db/models/sql/compiler.py", line 732, in execute_sql
cursor.execute(sql, params)
File "/home/daedalus/webapps/wowstatus/lib/python2开发者_如何学Go.6/django/db/backends/util.py", line 15, in execute
return self.cursor.execute(sql, params)
File "/home/daedalus/webapps/wowstatus/lib/python2.6/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
return self.cursor.execute(query, args)
django.db.utils.DatabaseError: current transaction is aborted, commands ignored until end of transaction block
You should reset your db state if something fails for example:
from django.db import transaction
@transaction.commit_manually
def Populate():
try:
Region(name=server['locale']).save()
print 'Added region: %(locale)s' % server
except IntegrityError:
transaction.rollback()
else:
transaction.commit()
I get this error sometimes when accessing the database from the django shell. I fix it by closing the connection:
from django.db import connection
connection.close()
cur = connection.cursor()
sql = 'select distinct category from uploads_document'
cur.execute(sql)
after I have made an error like 'select ditsinct ..'
精彩评论