重命名 auth_user 会破坏新设置的迁移

2023-12-29

遵循看起来像好建议 https://stackoverflow.com/questions/14904046/migrating-existing-auth-user-data-to-new-django-1-5-custom-user-model/15059338#15059338,我是从Django内置迁移过来的auth.User给我自己的app.User通过进行重命名的迁移auth_user to app_user。到目前为止一切顺利,效果很好。当我设置一台新机器时,问题就出现了。

In my settings.py I have AUTH_USER_MODEL = 'app.User'。正因为如此,当我跑步时syncdb, the auth_user表没有创建,所以当我migrate,迁移失败。

我发现解决这个问题的唯一方法是修改AUTH_USER_MODEL指向auth.User, run syncdb和迁移直到重命名迁移,然后更改AUTH_USER_MODEL返回,然后运行其余的迁移。

有办法解决这个问题吗?


根据您提到的问题,我首先尝试的方法是修改执行表重命名的迁移以检查是否应该执行重命名。不幸的是南不轻易合作 http://south.aeracode.org/ticket/1226有了这种检查。大多数高级操作如果失败,就会完全中止迁移。但是,您可以使用db.execute http://south.aeracode.org/wiki/db.execute and it will如果失败则引发异常。就像是:

from django.db.utils import ProgrammingError
from south.db import db

exists = False
db.start_transaction()
try:
    # Will fail if the destination table does not exist. 
    # Any typo here will yield incorrect results. Be careful.
    db.execute("select count(*) from auth_user")
    # If we get here, the table exists
    exists = True
except ProgrammingError:
    pass

# Always end the transaction we started, rollback or commit shouldn't matter.
db.rollback_transaction()

if exists:
    db.rename_table...
else:
    # The table does not exist, create new one.
    db.create_table...

我的测试表明,总是可以捕获 South 的数据库调用引发的错误。However,South 在 SQL 错误后不会清理。 (这是我最初在这个答案的第一个版本中错过的。)因此,即使捕获了异常,next将启动的SQL操作会发现连接处于错误状态。换句话说,失败的操作之后发生的操作将因为前一个操作失败而失败。这就是原因db.start_transaction() and db.rollback_transaction()来电。即使出现 SQL 错误,这也会使操作干净地结束。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重命名 auth_user 会破坏新设置的迁移 的相关文章

随机推荐