Django 批处理/批量更新或创建?

新手上路,请多包涵

我的数据库中有需要定期更新的数据。数据源返回当时可用的所有内容,因此将包括数据库中尚不存在的新数据。

当我遍历源数据时,如果可能的话,我不想进行 1000 次单独写入。

是否有诸如 update_or_create 但可以批量工作的东西?

一种想法是将 update_or_create 与手动事务结合使用,但我不确定这是否只是将单个写入排队,或者是否会将其全部组合到一个 SQL 插入中?

或者类似地可以使用 @commit_on_success() 在一个函数上使用 update_or_create 在循环中工作吗?

除了翻译数据并将其保存到模型之外,我没有对数据做任何事情。没有任何东西依赖于循环中存在的那个模型。

原文由 binarysmacker 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.2k
1 个回答

由于 Django 添加了对 bulk_update 的支持,现在这在某种程度上是可能的,尽管您需要为每个批次执行 3 次数据库调用(一次获取、一次批量创建和一次批量更新)。在这里为通用函数创建一个良好的接口有点具有挑战性,因为您希望该函数既支持高效查询又支持更新。这是我实现的一种方法,专为批量 update_or_create 而设计,其中您有许多公共标识键(可能为空)和一个批次之间不同的标识键。

这是作为基本模型上的方法实现的,但可以独立于该模型使用。这还假设基本模型在名为 updated_on 的模型上有一个 auto_now 时间戳;如果不是这种情况,假设这种情况的代码行已被注释以便于修改。

为了批量使用它,在调用它之前将你的更新分成批次。这也是一种绕过数据的方法,这些数据可以具有辅助标识符的少量值之一,而无需更改接口。

 class BaseModel(models.Model):
    updated_on = models.DateTimeField(auto_now=True)

    @classmethod
    def bulk_update_or_create(cls, common_keys, unique_key_name, unique_key_to_defaults):
        """
        common_keys: {field_name: field_value}
        unique_key_name: field_name
        unique_key_to_defaults: {field_value: {field_name: field_value}}

        ex. Event.bulk_update_or_create(
            {"organization": organization}, "external_id", {1234: {"started": True}}
        )
        """
        with transaction.atomic():
            filter_kwargs = dict(common_keys)
            filter_kwargs[f"{unique_key_name}__in"] = unique_key_to_defaults.keys()
            existing_objs = {
                getattr(obj, unique_key_name): obj
                for obj in cls.objects.filter(**filter_kwargs).select_for_update()
            }

            create_data = {
                k: v for k, v in unique_key_to_defaults.items() if k not in existing_objs
            }
            for unique_key_value, obj in create_data.items():
                obj[unique_key_name] = unique_key_value
                obj.update(common_keys)
            creates = [cls(**obj_data) for obj_data in create_data.values()]
            if creates:
                cls.objects.bulk_create(creates)

            # This set should contain the name of the `auto_now` field of the model
            update_fields = {"updated_on"}
            updates = []
            for key, obj in existing_objs.items():
                obj.update(unique_key_to_defaults[key], save=False)
                update_fields.update(unique_key_to_defaults[key].keys())
                updates.append(obj)
            if existing_objs:
                cls.objects.bulk_update(updates, update_fields)
        return len(creates), len(updates)

    def update(self, update_dict=None, save=True, **kwargs):
        """ Helper method to update objects """
        if not update_dict:
            update_dict = kwargs
        # This set should contain the name of the `auto_now` field of the model
        update_fields = {"updated_on"}
        for k, v in update_dict.items():
            setattr(self, k, v)
            update_fields.add(k)
        if save:
            self.save(update_fields=update_fields)

用法示例:

 class Event(BaseModel):
    organization = models.ForeignKey(Organization)
    external_id = models.IntegerField(unique=True)
    started = models.BooleanField()

organization = Organization.objects.get(...)
updates_by_external_id = {
    1234: {"started": True},
    2345: {"started": True},
    3456: {"started": False},
}
Event.bulk_update_or_create(
    {"organization": organization}, "external_id", updates_by_external_id
)

可能的竞争条件

上面的代码利用一个事务和 select-for-update 来防止更新的竞争条件。但是,如果两个线程或进程试图创建具有相同标识符的对象,则可能存在插入竞争条件。

简单的缓解措施是确保您的 common_keys 和您的 unique_key 的组合是数据库强制的唯一性约束(这是此功能的预期用途)。这可以通过使用 unique=True 引用字段的 unique_key 来实现,或者通过 unique_key 与由 UniqueConstraint 一起强制执行为唯一的 common_keys 的子集来实现。使用数据库强制的唯一性保护,如果多个线程试图执行冲突的创建,除了一个线程之外的所有线程都将失败并显示 IntegrityError 。由于封闭事务,失败的线程将不执行任何更改,并且可以安全地重试或忽略(失败的冲突创建可以只被视为先发生然后立即被覆盖的创建)。

如果无法利用唯一性约束,那么您将需要实施自己的并发控制或 锁定整个表

原文由 Zags 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题