gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:51:04 26 4
gpt4 key购买 nike

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

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

有没有类似 update_or_create 但可以批量工作的东西?

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

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

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

最佳答案

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

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

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

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
)

可能的竞争条件

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

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

如果无法利用唯一性约束,那么您将需要实现自己的并发控制或 lock the entire table

关于python - Django 批处理/批量更新或创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27047630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com