如何从django项目(及其所有表)中删除应用程序

gue*_*tli 8 python django database-migration django-apps

我想从django项目中删除一个应用程序.

我想删除

  • 应用程序的表格
  • 内容类型
  • 这些内容类型的外键使用

运行manage.py migrate app_to_remove zero不起作用:

django.db.migrations.migration.IrreversibleError: 
Operation <RunPython <function forwards_func at 0x7ff76075d668>> in
            fooapp.0007_add_bar is not reversible
Run Code Online (Sandbox Code Playgroud)

我想有几次迁移是不可逆的......

gue*_*tli 13

第一:删除代码中的引用

  • app_to_remove从中移除settings.INSTALLED_APPS
  • 删除urls.py其他地方的其他引用

第二:清理数据库

为您的django项目创建一个空迁移:

manage.py makemigrations your_django_project --empty
Run Code Online (Sandbox Code Playgroud)

编辑文件.这是一个模板:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('your_django_project', '0001_initial'),
    ]

    operations = [
        migrations.RunSQL('''
        drop if exists table app_to_remove_table1;
        drop if exists table app_to_remove_table2;
        ....
        delete from auth_permission where content_type_id in (select id from django_content_type where app_label = '{app_label}');
        delete from django_admin_log where content_type_id in (select id from django_content_type where app_label = '{app_label}');
        delete from reversion_version where content_type_id in (select id from django_content_type where app_label = '{app_label}');
        delete from django_content_type where app_label = '{app_label}';
        delete from django_migrations where app='{app_label}';
        '''.format(app_label='app_to_remove'))
    ]
Run Code Online (Sandbox Code Playgroud)

运行迁移,运行测试.

关于"drop if exists":你有两种情况:

  1. 生产系统:您想要删除表.
  2. 新的开发系统:这些系统从来没有这个应用程序,他们没有这个表:-)

  • 我正在使用带有PostgreSQL的Django 1.10.我会说**your_app**而不是your_django_project.然后,步骤的顺序是oposite:首先清理数据库(您需要安装应用程序才能创建迁移).接下来卸载应用程序.另外,在我的例子中,正确的语法是:`drop table if exists app_to_remove_table1; ...`https://www.postgresql.org/docs/8.2/static/sql-droptable.html最后,我不得不删除这行:`从reversion_version中删除......`. (5认同)