上来就干货!
在任意已经应用的app下创建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,包括虚拟环境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)
# 创建文件夹,并生成__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!"))
执行命令:python manage.py clearmigrations