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

Python Django批处理/批量更新或创建?,python,django,database,orm,Python,Django,Database,Orm,我的数据库里有数据,需要定期更新。数据源返回在该时间点可用的所有数据,因此将包括数据库中尚未包含的新数据 当我在源数据中循环时,如果可能的话,我不想进行1000次单独写入 是否有类似于update\u或\u create的东西可以成批工作 一个想法是将update\u或\u create与手动事务结合使用,但我不确定这只是将单个写入排队,还是将所有写入合并到一个SQL插入中 或者类似地,在循环内部对具有update\u或=self.size:#允许大小为0 self.toggle=非self.t

我的数据库里有数据,需要定期更新。数据源返回在该时间点可用的所有数据,因此将包括数据库中尚未包含的新数据

当我在源数据中循环时,如果可能的话,我不想进行1000次单独写入

是否有类似于
update\u或\u create
的东西可以成批工作

一个想法是将
update\u或\u create
与手动事务结合使用,但我不确定这只是将单个写入排队,还是将所有写入合并到一个SQL插入中

或者类似地,在循环内部对具有
update\u或
的函数使用
@commit\u on\u success()


除了转换数据并将其保存到模型之外,我不会对数据做任何事情。任何东西都不依赖于循环过程中存在的模型

批量更新将是一个upsert命令,正如@imposeren所说,Postgres 9.5为您提供了这种能力。我认为MySQL5.7也会根据您的具体需求来做(请参阅)。也就是说,使用db游标可能是最简单的。这没什么错,当ORM还不够的时候,它就在那里

沿着这条思路应该会奏效。这是psuedo-ish代码,所以不要只是剪切粘贴它,而是为你准备的概念

类GroupByChunk(对象):
定义初始值(自身,大小):
self.count=0
self.size=大小
self.toggle=False
定义调用(self,*args,**kwargs):
如果self.count>=self.size:#允许大小为0
self.toggle=非self.toggle
self.count=0
self.count+=1
返回自切换
def批处理更新(数据库结果、upsert\U sql):
使用transaction.atomic():
cursor=connection.cursor()
对于itertools.groupby(db_results,GroupByChunk(size=1000))中的块:
cursor.execute\u many(upsert\u sql,chunk)
这里的假设是:

  • db_results
    是某种结果迭代器,在列表或字典中
  • 来自
    db_results
    的结果可以直接输入原始sql exec语句
  • 如果任何批更新失败,您将回滚所有批更新。如果要将每个区块的
    移动到,只需将
    with
    块向下推一点

由于Django增加了对批量更新的支持,现在这在某种程度上是可能的,尽管您需要在每个批处理中进行3次数据库调用(一次get、一次批量创建和一次批量更新)。在这里为通用函数创建一个良好的接口有点困难,因为您希望该函数既支持高效查询,又支持更新。这里是我实现的一个方法,它是为批量更新或创建而设计的,在批量更新或创建中,您有许多通用标识键(可能为空)和一个标识键,这些标识键在批处理中有所不同

这是在基础模型上作为方法实现的,但可以独立于基础模型使用。这还假设基础模型在名为
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)
            
            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
)

我认为,在大多数sql服务器中,没有一个单一的更新或创建查询。中有一个,但django不支持它。事务不会导致“单一”查询。它只会确保如果一个查询失败,所有查询都会失败。事实上,它会减慢所有querys.Upd的速度。我对交易的看法是错误的。对所有操作使用单个事务将加快写入速度。这至少适用于postgres和sqlite: