Django:使用关系中的值更新多行

Django: Update multiple rows with value from relation

我们的数据库中有数千行都需要应用数据库迁移。 我们有很多行可以追溯到 8 年前,我们在每个单独的实例上 运行 save() 真的不可行,如这里的示例所示:

update_list = OrderProduct.objects.filter(
    product__isnull=False,
    title="unnamed")

for op in update_list:
    op.title = op.product.title
    op.save()  # We would prefer a update() query rather than individual saves

所以我们正在尝试使用数据库查询来执行此操作。我知道 F()update() 中使用它时不支持连接,这就是为什么我试图在以下方面变得聪明:

OrderProduct.objects\
    .filter(title="unnamed", product__isnull=False)\
    .annotate(copy_title=F('product__title'))\
    .update(title=F('copy_title'))

不幸的是,这不起作用,所以我想知道是否有一种简单的方法可以使用 django update() 来实现这一点,而不是循环遍历每一行。

进口:

from django.db import transaction
from bulk_update.helper import bulk_update

您需要将您的行放入一个列表,该列表是函数的参数 create_objects & update_objects

你可以试试bulk_create:

    def create_objects(create_objects: list, chunk_size=2000):
    if len(create_objects):
        with transaction.atomic():
            model_cls: Model = create_objects[0].__class__
            for chunk_list in ModelHelpers.chunk_iterate(create_objects, chunk_size):
                model_cls.objects.bulk_create(chunk_list)

    return create_objects

和bulk_update:

    @staticmethod
    def update_objects(update_objects: list, update_fields=None, chunk_size=2000):
    if update_objects:
        with transaction.atomic():
            for chunk_list in ModelHelpers.chunk_iterate(update_objects, chunk_size):
                bulk_update(chunk_list, update_fields=update_fields)

您需要 chunk_iterate 功能:

    @staticmethod
    def chunk_iterate(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]

希望对您有所帮助,