gpt4 book ai didi

python - django makemigrations 覆盖以创建具有自定义名称的迁移文件

转载 作者:行者123 更新时间:2023-12-02 16:38:28 27 4
gpt4 key购买 nike

我有一个 python2.7 django 项目(我知道,我在 20 世纪!),其中有一些模型。我需要重写 makemigrations,以便迁移文件名的格式为 0001.py、0002.py 等,而不像默认情况下发生的 0001_initial.py、0002_model1.py 等。

我已经了解了如何创建自定义 manage.py 命令并且我能够覆盖 makemigrations 命令。目前,我的自定义命令 (python2.7) 代码如下所示:

path/to/project/app/management/commands/makemigrations.py

from django.core.management.commands.makemigrations import Command as CoreMakeMigrationsCommand

class Command(CoreMakeMigrationsCommand):
def handle(self, *args, **options):
super(Command, self).handle(*args, **options)

目前它只是调用原始的 makemigrations。我需要能够修改 autodetector.py(它是 makemigrations 流程的一部分)如何决定文件命名的行为。在此文件中,有如下所示的方法 suggest_name:

@classmethod
def suggest_name(cls, ops):
"""
Given a set of operations, suggest a name for the migration they might
represent. Names are not guaranteed to be unique, but put some effort
into the fallback name to avoid VCS conflicts if possible.
"""
if len(ops) == 1:
if isinstance(ops[0], operations.CreateModel):
return ops[0].name_lower
elif isinstance(ops[0], operations.DeleteModel):
return "delete_%s" % ops[0].name_lower
elif isinstance(ops[0], operations.AddField):
return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
elif isinstance(ops[0], operations.RemoveField):
return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower)
elif ops:
if all(isinstance(o, operations.CreateModel) for o in ops):
return "_".join(sorted(o.name_lower for o in ops))
return "auto_%s" % get_migration_name_timestamp()

上面的代码是从这里调用的,在同一个文件中的另一个方法arrange_for_graph:

            for i, migration in enumerate(migrations):
if i == 0 and app_leaf:
migration.dependencies.append(app_leaf)
if i == 0 and not app_leaf:
new_name = "0001_%s" % migration_name if migration_name else "0001_initial"
else:
new_name = "%04i_%s" % (
next_number,
migration_name or self.suggest_name(migration.operations)[:100],
)

我是重写核心文件的新手,无法弄清楚如何只重写我原来的自定义命令文件中的这一部分,以便满足我的要求?

此外,请告知这将如何影响对 makemigrations 的后续调用,因为它们将依赖于新的迁移文件集(具有修改后的名称)。

谢谢

最佳答案

好的,这就是我的做法。

创建一个 makemigrations.py 文件(如 django 文档中所示,用于覆盖 manage.py 命令),在其中创建一个继承“django.core.management.commands.makemigrations.Command”的 Command 类并覆盖方法 write_migration_files,如下图:

from django.core.management.commands.makemigrations import Command as CoreMakeMigrationsCommand


class Command(CoreMakeMigrationsCommand):
def write_migration_files(self, changes):
for item in changes.values():
print('Overriding default names of migrations supplied by django core')
item[0].name = item[0].name.split('_')[0]
super(Command, self).write_migration_files(changes)

关于python - django makemigrations 覆盖以创建具有自定义名称的迁移文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62189966/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com