私は毎日いくつかの大きなjsonファイルからデータをインポートする必要があるDjango 1.1アプリを持っています。アイデアを出すために、これらのファイルの1つは100 Mb以上で、Postgresqlデータベースにインポートされる90,000のエントリを持っています。PostgresqlデータベースのパフォーマンスをDjangoで最適化しますか?
私が抱えている問題は、データをインポートするのに実際には時間がかかり、つまり数時間かかることです。その数のエントリをデータベースに書き込むのにある程度の時間がかかることは予想されましたが、それほど長くはないので、私が本質的に間違ったことをしていると思います。私は同様のスタックエクスチェンジに関する質問を読んでおり、提案されている解決策は、私がすでにやっている.save()
の代わりにtransaction.commit_manually
またはtransaction.commit_on_success
のデコレータをバッチでコミットすることを提案しています。
私は何か間違っている(バッチが大きすぎる、外来キーが多すぎるなど...)か、私はちょうどDjangoモデルから離れるべきかどうか疑問に思っています。この機能を使用し、DB APIを直接使用します。任意のアイデアや提案?
ここは、私がデータをインポートするときに対処しています基本モデル(私は簡単のために元のコード内のフィールドの一部を削除した)
class Template(models.Model):
template_name = models.TextField(_("Name"), max_length=70)
sourcepackage = models.TextField(_("Source package"), max_length=70)
translation_domain = models.TextField(_("Domain"), max_length=70)
total = models.IntegerField(_("Total"))
enabled = models.BooleanField(_("Enabled"))
priority = models.IntegerField(_("Priority"))
release = models.ForeignKey(Release)
class Translation(models.Model):
release = models.ForeignKey(Release)
template = models.ForeignKey(Template)
language = models.ForeignKey(Language)
translated = models.IntegerField(_("Translated"))
されており、ここではコードのビットがあることです完了するまでに年齢を取るようだ:
@transaction.commit_manually
def add_translations(translation_data, lp_translation):
releases = Release.objects.all()
# There are 5 releases
for release in releases:
# translation_data has about 90K entries
# this is the part that takes a long time
for lp_translation in translation_data:
try:
language = Language.objects.get(
code=lp_translation['language'])
except Language.DoesNotExist:
continue
translation = Translation(
template=Template.objects.get(
sourcepackage=lp_translation['sourcepackage'],
template_name=lp_translation['template_name'],
translation_domain=\
lp_translation['translation_domain'],
release=release),
translated=lp_translation['translated'],
language=language,
release=release,
)
translation.save()
# I realize I should commit every n entries
transaction.commit()
# I've also got another bit of code to fill in some data I'm
# not getting from the json files
# Add missing templates
languages = Language.objects.filter(visible=True)
languages_total = len(languages)
for language in languages:
templates = Template.objects.filter(release=release)
for template in templates:
try:
translation = Translation.objects.get(
template=template,
language=language,
release=release)
except Translation.DoesNotExist:
translation = Translation(template=template,
language=language,
release=release,
translated=0,
untranslated=0)
translation.save()
transaction.commit()
この最近の回答をご覧ください。これにはいくつかの便利な一般的なヒントがあります。 http://stackoverflow.com/questions/9407442/optimise-postgresql-for-fast-testing/9407940#comment11914305_9407940 –
質問の2番目の部分は[フォローアップの質問]に分割されました(http:// stackoverflow。 com/q/9447506/939860) –