上來就干貨!
在任意已經(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é)果