You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优化按步长批量创建Django对象的函数以减少重复代码?

优化批量创建Django对象的函数写法

你当前的函数确实存在重复代码问题——分别处理整批次和剩余批次时,重复调用了TodoFactory.build_batch()和Todo.objects.bulk_create(todos)。可以通过统一批次列表+单次循环的方式重构,消除重复逻辑:

优化后的代码

def create_todos_in_batch(total, step):
    # 生成所有需要处理的批次大小列表
    batches = [step] * (total // step)
    # 处理剩余不足一个step的部分
    if remainder := total % step:
        batches.append(remainder)
    
    current_count = 0
    for batch_size in batches:
        end_count = current_count + batch_size
        print(f"Inserting {current_count:,} to {end_count:,}")
        todos = TodoFactory.build_batch(batch_size)
        Todo.objects.bulk_create(todos)
        current_count = end_count

重构思路

  1. 统一批次处理:先把所有要创建的批次大小整理成一个列表,不管是整step的批次还是剩余的小批次,都放到同一个列表中
  2. 单次循环执行:遍历这个批次列表,统一执行打印、生成对象、批量插入的逻辑,彻底消除重复代码
  3. 简化计数逻辑:用current_count跟踪当前已创建的对象数量,每次循环更新,避免原代码中i * step的计算方式

原测试代码依然适用

你编写的单元测试不需要任何修改,因为重构后的函数功能和原函数完全一致,只是代码结构更简洁:

@pytest.mark.parametrize(
    "total, step",
    [
        (100, 20),
        (1_000, 100),
        (10_000, 1_000),
    ],
)
@pytest.mark.django_db
def test_create_in_batch(total, step):
    create_todos_in_batch(total=total, step=step)
    count = Todo.objects.count()
    assert count == total, f"{count:,} != {total:,}"

内容的提问来源于stack exchange,提问作者Johnny Metz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:10:49