How to 'bulk update' with Django?

前端 未结 5 1053
挽巷
挽巷 2020-11-28 04:40

I\'d like to update a table with Django - something like this in raw SQL:

update tbl_name set name = \'foo\' where name = \'bar\'

My first

5条回答
  •  执念已碎
    2020-11-28 05:33

    Django 2.2 version now has a bulk_update method (release notes).

    https://docs.djangoproject.com/en/stable/ref/models/querysets/#bulk-update

    Example:

    # get a pk: record dictionary of existing records
    updates = YourModel.objects.filter(...).in_bulk()
    ....
    # do something with the updates dict
    ....
    if hasattr(YourModel.objects, 'bulk_update') and updates:
        # Use the new method
        YourModel.objects.bulk_update(updates.values(), [list the fields to update], batch_size=100)
    else:
        # The old & slow way
        with transaction.atomic():
            for obj in updates.values():
                obj.save(update_fields=[list the fields to update])
    

提交回复
热议问题