通过 shell 在 Django 中插入大量数据

Inserting large amounts of data in Django via the shell

我目前有一个使用 postgres 设置的 Django 环境。我正在尝试 运行 shell 中的一个简单脚本,但完成时间太长。

在 Django 的 postgres table 中是否有更新所有记录的有效方法?

我的 table 叫做城市,它包含大约 200,000 个城市。

这是我 运行 在 python manage.py shell 中使用的脚本:

from locations.models import City
from django.template.defaultfilters import slugify
counter = 0
for obj in City.objects.all():
    counter = counter + 1
    if counter % 1000 == 0:
        print counter
    obj.city_name_slug = slugify(obj.city_name) + "-" + slugify(obj.region)
    obj.save()

使用事务处理,它会加快您的查询速度。也用 filter().update() 组合替换 obj.save() 调用,这是更改 DB 中单个字段的最快方法:

from locations.models import City
from django.db import transaction
from django.template.defaultfilters import slugify
counter = 0
with transaction.atomic():
    for obj in City.objects.all():
        counter = counter + 1
        if counter % 1000 == 0:
            print counter
        slug = slugify(obj.city_name) + "-" + slugify(obj.region)
        City.objects.filter(pk=obj.pk).update(city_name_slug=slug)