开发者

Why am I getting duplicate key integrity errors from Django's get_or_create?

UPDATE: Found the answer here, and the suggested work-around works for me: How do I deal with this race condition in django?

Hello all. Observe the following code:

while True:
    User.objects.get_or_create(email='foo-%d@example.com' % int(time()))

Where User is a standard Django model with unique=True for email. When I run this code in two shells at the same time within a few seconds I get an error like:

IntegrityError: (1062, "Duplicate entry 'foo-1292519049@example.com' for key 'email'")

It was my impression that get_or_create() was specifically designed to avoid this situation. Looking at the code it seems to me that it should be working. It does a get() first, then if that fails enters a transaction and tries a save(). If that fails it rolls back and tries a get() again. If that fails then the exception from the save() is thrown, which seems to be what I'm getting.

Some useful info - I'm running Django v1.1.0 with My开发者_StackOverflow中文版SQL v5.1.39 and InnoDB. Our InnoDB isolation level is REPEATABLE-READ.

Thanks for the help!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜