Django:如何做get_or_create()以线程安全的方式? [英] Django: how to do get_or_create() in a threadsafe way?
问题描述
在我的Django应用程序中,我经常需要做类似于 get_or_create()
的事情。例如
In my Django app very often I need to do something similar to get_or_create()
. E.g.,
用户提交标签。需要看看是否
该标签已经在数据库中。
如果没有,为它创建一个新记录。如果
,它只是更新现有的
记录。
User submits a tag. Need to see if that tag already is in the database. If not, create a new record for it. If it is, just update the existing record.
$ c> get_or_create()看起来不是线程安全的。线程A检查和查找记录X不存在。然后线程B检查并发现记录X不存在。现在线程A和线程B都将创建一个新的记录X.
But looking into the doc for get_or_create()
it looks like it's not threadsafe. Thread A checks and finds Record X does not exist. Then Thread B checks and finds that Record X does not exist. Now both Thread A and Thread B will create a new Record X.
这是一个很常见的情况。如何以线程安全的方式处理它?
This must be a very common situation. How do I handle it in a threadsafe way?
推荐答案
这必须是很常见的情况。如何以线程安全的方式处理它?</ p>
This must be a very common situation. How do I handle it in a threadsafe way?
是的。
SQL中的标准解决方案是简单地尝试创建记录。如果它工作,这是好的。继续。
The "standard" solution in SQL is to simply attempt to create the record. If it works, that's good. Keep going.
如果尝试创建记录从RDBMS获取重复异常,则执行SELECT并继续。
If an attempt to create a record gets a "duplicate" exception from the RDBMS, then do a SELECT and keep going.
然而,Django有一个ORM层,它有自己的缓存。所以逻辑被反转,使常见的情况下直接和快速工作,而不常见的情况(副本)引发罕见的异常。
Django, however, has an ORM layer, with it's own cache. So the logic is inverted to make the common case work directly and quickly and the uncommon case (the duplicate) raise a rare exception.
这篇关于Django:如何做get_or_create()以线程安全的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!