djangoget_or_create非线程安全

编程

背景

  • 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.

"""

# 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(**kwargs), False #先查询,找不到则创建,存在并发问题。

except self.model.DoesNotExist:

params = self._extract_model_params(defaults, **kwargs)

return self._create_object_from_params(kwargs, params)

处理方式:

from django.db import transaction

@transaction.atomic

def atomic_get_create_object(data=None):

"""

:param data:

:return:

"""

obj, is_create = RunnerInfo.objects.get_or_create(**data)

return obj, is_create

以上是 djangoget_or_create非线程安全 的全部内容, 来源链接: utcz.com/z/519124.html

回到顶部