我做了一個模塊,它解析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