由于 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()
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
)