簡體   English   中英

如何處理 Django 遷移中的異常?

[英]How to handle exceptions in a Django migration?

如何在 Django 遷移中捕獲異常?

我有一個遷移,由於各種遺留原因,我預計有時會失敗。 在這種情況下,我希望能夠捕獲該錯誤並運行一些錯誤處理代碼。

具體來說,我正在重命名一個表,有時目標表已經存在,我想合並舊表和新表的內容,然后刪除舊表。

我正在運行 Django 1.7 (:(),我們正計划升級到 1.8,但還沒有發生。

我的遷移是:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

    dependencies = [
        ('main', '0007_migration_name'),
    ]

    operations = [
        migrations.AlterModelTable(
            name='table_name',
            table='LegacyTableName',
        ),
    ]

當我運行這個時,我得到

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File ".../django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File ".../django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File ".../django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File ".../django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File ".../django/core/management/commands/migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File ".../django/db/migrations/executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File ".../django/db/migrations/executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File ".../django/db/migrations/migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File ".../django/db/migrations/operations/models.py", line 236, in database_forwards
    new_model._meta.db_table,
  File ".../django/db/backends/schema.py", line 350, in alter_db_table
    "new_table": self.quote_name(new_db_table),
  File ".../django/db/backends/schema.py", line 111, in execute
    cursor.execute(sql, params)
  File ".../django/db/backends/utils.py", line 81, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File ".../django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File ".../django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File ".../django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File ".../django/db/backends/mysql/base.py", line 129, in execute
    return self.cursor.execute(query, args)
  File ".../MySQLdb/cursors.py", line 226, in execute
    self.errorhandler(self, exc, value)
  File ".../MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorvalue
django.db.utils.OperationalError: (1050, "Table 'LegacyTableName' already exists")

遷移本身提供的只是operations列表, 文檔中似乎沒有可選的錯誤處理參數。

如何捕獲 OperationalError 以便我可以運行一些 Python 來合並表?

嘗試在 Python 中捕獲數據庫異常的問題在於它們可能不夠具體——例如, OperationalError可能由於各種原因而出現(其中只有一個是表名已更改)。

我建議您不要嘗試捕獲異常,而是編寫自己的遷移函數來執行任何必要的檢查/修改。 請參閱有關RunPython文檔

這通常是您用於創建數據遷移、運行自定義數據更新和更改以及您需要訪問 ORM 和/或 Python 代碼的任何其他操作的操作。

在您的情況下,您將編寫一個函數來檢查表是否存在並針對任一情況執行一些操作。

編寫這些函數時需要注意一些特定於數據庫的問題,例如:

例如,在 PostgreSQL 上,您應該避免在同一遷移中組合模式更改和 RunPython 操作,否則您可能會遇到錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM