我做了一个模块,它解析xml文件并更新或在django数据库(pgsql)中创建数据。Django - 非常慢的查询
当数据导入/更新完成时,我尝试更新我的对象的一些元数据。
我使用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()
虽然这是一个重要的通知,这是不回答OP的问题。这个事实使得这是一个评论,而不是一个答案。因此,最好将此作为评论添加并删除此答案,或更新它以解决OP要求的答案。 – FallenAngel
为什么不回答这个问题? – geekazoid
因为你正在谈论*如何设计一个系统的非常基本的概念*,OP询问*他如何能够__优化他的现有系统* – FallenAngel