0

我制作了一个模块,它解析 xml 文件并在 django db (pgsql) 中更新或创建数据。

数据导入/更新完成后,我尝试更新我的对象的一些元数据。

我将 django-mptt 用于树结构,而我的元数据更新器用于在我的对象之间创建这样的结构。

用来自其他外键的数据填充父级需要大约 1 秒的时间真的很慢。

我该如何优化呢?

for index, place in enumerate(Place.objects.filter(type=Place.TOWN, town_id_equal=True)):
    place.parent = place.second_order_division
    place.save()

    print index
    if index % 5000 == 0:
        transaction.commit()
transaction.commit()

transaction.set_autocommit(False)
for index, place in enumerate(Place.objects.filter(type=Place.TOWN, town_id_equal=False,
                                                   parent__isnull=True)):

    place.parent = Place.objects.get(town_id=place.town_id_extra)
    place.save()

    print index
    if index % 5000 == 0:
        transaction.commit()
transaction.commit()


class Place(MPTTModel):
    first_order_division = models.ForeignKey("self", null=True, blank=True, verbose_name=u"Województwo",
                                             related_name="voivodeships")
    second_order_division = models.ForeignKey("self", null=True, blank=True, verbose_name=u"Powiat",
                                              related_name="counties")
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

编辑:

我像这样更新了第一个函数:

transaction.set_autocommit(False)
for index, obj in enumerate(Place.objects.filter(type=Place.COUNTY)):
    data = Place.objects.filter(second_order_division=obj, type=Place.TOWN, town_id_equal=True)
    data.update(parent=obj)
    print index
    transaction.commit()
4

2 回答 2

1

而不是使用循环,你应该做批量更新,比如

对于第一笔交易,您可以使用以下 Django 查询替换您的交易:

Place.objects.filter(type=Place.TOWN, town_id_equal=True).update(parent=F('second_order_division'))

对于第二笔交易,由于再次查询 Place 模型,我们无法应用批量更新。为此,您应该做一些事情来节省每次循环中的“Place.objects.get(town_id=place.town_id_extra)”查询。

或者可以从这个博客中获得帮助

于 2014-01-17T11:35:50.633 回答
-1

回答一个更普遍的问题,提高几乎任何类型系统性能的一种策略是:

最小化系统动态部分之间的交互

就是这样:通过 HTTP 请求、数据库查询等最大限度地减少交互。在您的情况下,您正在对数据库执行多个查询,这些查询可以轻松减少到更少(可能是一两个)。

于 2014-01-17T13:55:01.633 回答