IM,我已经看到了这个问题的几个帖子已经地名释义,它的一个MySQL的问题,所以我也跟着这个帖子 http://www.no-ack.org/2010/07/mysql-transactions-and-django.htmlDjango的IntegrityError与具有Django的get_or_create问题get_or_create
这基本上说,get_or_create
将返回由于MySQL的缺省事务隔离度为REPEATABLE READ
,因此同时创建对象时为IntegrityError
。
我做的帖子建议将transaction-isolation = READ-COMMITTED
添加到我的 /etc/mysql/my.cnf
文件中,但得到了同样的错误。所以即时通讯想知道是否有任何其他解决方案。
这里有一个样品模型复制的问题
class Author(models.Model):
name = models.CharField(max_length=100, unique=True)
class Book(models.Model):
name = models.CharField(max_length=100, unique=True)
author = models.ForeingKey(Author)
如果我有作者和图书的一个长长的清单,一些反复。我运行一个forloop来遍历每个作者/书使用get_or_create来创建或获取各自的对象,它会抛出一个IntegrityError。
的循环是类似的东西来..
authors = ['Author1', 'Author2', 'Author3', 'Author4', 'Author5']
books = ['book1', 'book2', 'book3', 'book4', 'book5']
for author, book in zip(authors, books):
author = Author.objects.get_or_create(name=author)[0]
author.book_set.get_or_create(name=book) # Error happens here
您能否显示您在循环中使用的代码? –
我不确定当你执行'author.book_set.get_or_create(name = book)'时会发生什么。我个人会更明确地这样做:'Book.objects.get_or_create(name = book,defaults = {'author':author})''或类似的东西。你能发布你的确切的错误?可能有帮助。 – Stefano