LoginSignup
9
5

More than 1 year has passed since last update.

DjangoでDBを一括更新する

Posted at

Djangoのbulk_update

DBのクレンジング作業などで一括更新する時、Djangoであればbulk_updateが使用できる。

Object.objects.bulk_update(object_list, fields=['name'])

第一引数には更新対象のobjectのリスト、fieldsには更新したいカラムを指定する。
この時、fieldsに設定しないカラムは更新されない。

bulk_updateで実行されるクエリ

では、bulk_updateではどのようなクエリが流れるだろうか。
以下のようなモデルに対して、bulk_updateを流してみる。

class Customer(models.Model):
    name = models.CharField(max_length=255)
    rate = models.IntegerField(default=0)
from polls.models import Customer
import random

def run():
    customers = Customer.objects.all()

    update_customer_list = []

    for customer in customers:
        customer.rate = random.randrange(10)

        update_customer_list.append(customer)

    Customer.objects.bulk_update(update_customer_list, fields=['rate'])

流れるupdateは以下の通り。

UPDATE `customer` SET `rate` = CASE WHEN (`customer`.`id` = 1) THEN 5 WHEN (`customer`.`id` = 2) THEN 4 WHEN (`customer`.`id` = 3) THEN 3 ELSE NULL END WHERE `customer`.`id` IN (1, 2, 3);

更新対象をWhere句で選択して、更新値はcase句で区切っていく形。
1回ずつsaveする形よりは実行は早い。

9
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5