Rob*_*juh 5 python django django-migrations
Django 提供了一个非常好的功能makemigrations,它可以根据模型的变化创建迁移文件。我们正在开发一个模块,我们将在其中生成自定义迁移。
我在 Django 文档中没有找到太多关于创建自定义迁移的信息。有关于Operation可以产生迁移的各种类的文档,但没有关于创建Operation可以产生自定义迁移的自定义类的文档。
autodetector用于生成新迁移的模块似乎也没有为添加自定义Operation类留下太多空间:https : //github.com/django/django/blob/master/django/db/migrations/autodetector.py#L160
这似乎是完全静态的。是否有其他方法来生成自定义迁移,也许是通过使用带有自定义管理命令的现有类?
您可以创建一个自定义类来挂钩 makemigrations 类并添加自定义迁移内容,然后使用“runscript”命令执行。下面是一个示例模块,其中文件名为 custom_migrations.py 并位于应用程序之一的“scripts”文件夹中:
from django.core.management.commands.makemigrations import Command
"""
To invoke this script use:
manage.py runscript custom_migrations --script-args [app_label [app_label ...]] name=my_special_migration verbosity=1
"""
class MyMigrationMaker(Command):
'''
Override the write method to add more stuff before finishing
'''
def write_migration_files(self, changes):
print("Do some stuff to \"changes\" object here...")
super().write_migration_files(changes)
def run(*args):
nargs = []
kwargs = {}
# Preload some options with defaults and then can be overridden in the args parsing
kwargs['empty'] = True
kwargs['verbosity'] = 1
kwargs['interactive'] = True
kwargs['dry_run'] = False
kwargs['merge'] = False
kwargs['name'] = 'custom_migration'
kwargs['check_changes'] = False
for arg in args:
kwarg = arg.split('=', 1)
if len(kwarg) > 1:
val = kwarg[1]
if val == "True":
arg_val = True
elif val == "False":
arg_val = False
elif val.isdigits():
arg_val = int(val)
else:
arg_val = val
the_kwargs[kwarg[0]] = arg_val
else:
nargs.append(arg)
MyMigrationMaker().handle(*nargs, **kwargs)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2342 次 |
| 最近记录: |