繁体   English   中英

带有get_or_create的Django IntegrityError

[英]Django IntegrityError with get_or_create

我在Django的get_or_create上遇到问题,我已经在一些帖子中看到了这个问题,这些帖子已经说明了它是MySQL的问题,所以我关注了这篇文章http://www.no-ack.org/2010/07/mysql-transactions- and-django.html

基本上说,由于MySQL默认的REPEATABLE READ事务隔离,并发创建对象时get_or_create将返回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

通常,不应将get_or_create与数据库中不唯一的字段一起使用。 避免此问题的一种方法是强制名称字段的唯一性:

class Author(models.Model):
    name = models.CharField(max_length=100, unique=True)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM