django get_or_create()不是线程安全的

作者: jarhmj | 来源:发表于2019-01-29 11:35 被阅读1次

最近数据库出现了莫名的BUG,一条记录会同时创建两次。

为了解决这个问题,首先看了一下代码,代码用了get_or_create()这个方法,翻看了源码:

    def get_or_create(self, defaults=None, **kwargs):
        """
        Look up an object with the given kwargs, creating one if necessary.
        Return a tuple of (object, created), where created is a boolean
        specifying whether an object was created.
        """
        lookup, params = self._extract_model_params(defaults, **kwargs)
        # The get() needs to be targeted at the write database in order
        # to avoid potential transaction consistency problems.
        self._for_write = True
        try:
            return self.get(**lookup), False
        except self.model.DoesNotExist:
            return self._create_object_from_params(lookup, params)

原来这个方法不是原子的,如果并发操作会出现问题(就像我的创建了两次)。不过这个方法的名字太“原子”了,会让人误以为是线程安全的,如果改成get_or_create_unsafely()可能会让人谨慎起来。

接着,我查看了一下日志,果真是有并发的请求,难怪会出现这样的问题。

解决方案:

  1. 配合事务一起使用
  2. 在model层加限制uniqueunique_together

大家如果喜欢,欢迎点赞分享评论哦!😘

相关文章

  • django get_or_create()不是线程安全的

    最近数据库出现了莫名的BUG,一条记录会同时创建两次。 为了解决这个问题,首先看了一下代码,代码用了get_or_...

  • Java 的 StringBuffer 和 StringBuil

    区别就是:线程安全,StringBuffer 是线程安全的,StringBuilder 不是线程安全的。 他俩的实...

  • HashMap相关

    HashMap是数组+链表 1.HashMap不是线程安全,为什么不是线程安全的呢? 多线程put,多线程reha...

  • 专题一 Hashtable、ConcurrentHashMap

    线程安全的HashMap,ConcurrentHashMap HashMap是线程安全的吗?: 不是。多线程环境下...

  • HashMap问答

    HashMap是不是线程安全? 不是线程安全的。 为什么不安全? 线程不安全的两个添加是,数据可共享、可修改。Ha...

  • iOS-线程安全探究

    为什么CFRunLoopRef是线程安全的,而基于此的NSRunLoop却不是线程安全的呢? 线程安全时多线程领域...

  • JAVA 线程安全

    线程安全定义 一个类在可以被多个线程安全调用时就是线程安全的。 线程安全分类 线程安全不是一个非真即假的命题,可以...

  • iOS CoreData多线程(一)☂️

    CoreData与线程安全 CoreData不是线程安全的,对于ManagedObject以及ManagedObj...

  • ArrayIndexOutOfBoundsException异常

    Hashmap不是线程安全的,不能并发使用android.util.ArrayMap 可能也不是线程安全的,不能并...

  • NSNotification

    Objective-C 代码 Swift 代码 线程安全 NSNotification 是线程安全的,但也不是绝对...

网友评论

    本文标题:django get_or_create()不是线程安全的

    本文链接:https://www.haomeiwen.com/subject/teztsqtx.html