Django提供了一个非常好的特性,称为makemigrations
,它将根据模型中的更改创建迁移文件。我们正在开发一个模块,我们希望在其中生成自定义迁移。在
我在Django文档中没有找到很多关于创建自定义迁移的信息。有关于各种可以生成迁移的Operation
类的文档,但是没有关于创建可以生成自定义迁移的Operation
类的内容。在
用于生成新迁移的autodetector
模块似乎也没有为添加定制的Operation
类留下太多空间:https://github.com/django/django/blob/master/django/db/migrations/autodetector.py#L160
看来这是完全静止的。是否有其他方法生成自定义迁移,可能是通过使用带有自定义管理命令的现有类?在
如果您不愿意使用Django内部构件,另一种方法是使用下面的脚本通过调用一个随机方法生成一个迁移文件,该方法将生成您希望在迁移中运行的Python代码,并将其插入到一个有效的迁移文件中,该文件将成为标准Django迁移的一部分。 你有一个名为“xxx”的应用程序,你在一个文件xxx/scripts中有一个方法/测试.py看起来像这样:
。。。您调用了存储在xxx/scripts/custom中的本文底部显示的脚本_迁移.py使用以下命令
^{pr2}$然后在xxx/migrations中得到一个迁移文件,该文件具有适当的编号顺序(比如0004_宾果)看起来像这样:
脚本如下:
您可以创建一个自定义类来钩住makemigrations类,然后添加您的自定义迁移内容,然后使用“runscript”命令执行。下面是一个示例模块,其中文件名为custom_迁移.py并位于你的某个应用程序的“脚本”文件夹中:
相关问题 更多 >
编程相关推荐