Django重置migrations

上來就干貨!

在任意已經(jīng)應(yīng)用的app下創(chuàng)建management/commands/clearmigrations.py文件

import os
import sys
import shutil
from django.core.management.base import BaseCommand
from django.conf import settings
from django.apps import apps


class Command(BaseCommand):
    help = "Clear all migration files in project."

    def get_apps(self):
        for app in apps.get_app_configs():
            # 只刪除自己的app下的migrations文件夾
            # path = os.path.join(
            #     settings.BASE_DIR, app.name.replace(".", "/"), "migrations"
            # )

            # 刪除所有app,包括虛擬環(huán)境app下的migrations文件夾
            path = os.path.join(app.path, "migrations")
            if os.path.exists(path):
                yield app, path

    def handle(self, *args, **options):
        for app, path in self.get_apps():
            # 遞歸刪除所有文件及其路徑(刪除整個文件夾)
            shutil.rmtree(path)
            # 創(chuàng)建文件夾,并生成__init__.py文件
            os.makedirs(path)
            with open(os.path.join(path, "__init__.py"), "w+") as file:
                file.write("")
            self.stdout.write(self.style.SUCCESS(f"Clear {path}"))

        self.stdout.write(self.style.SUCCESS("Successfully cleared!"))
目錄結(jié)構(gòu)

執(zhí)行命令:python manage.py clearmigrations

執(zhí)行結(jié)果
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容