How to remove an app from a django projects (and all its tables)

时间:2016-03-02 10:57:06

标签: python django database-migration django-apps

I want to remove an app from a django project.

I want to remove

  • the tables of the app
  • the content-types
  • foreign-key usages of these content-types

Running manage.py migrate app_to_remove zero does not work:

django.db.migrations.migration.IrreversibleError: 
Operation <RunPython <function forwards_func at 0x7ff76075d668>> in
            fooapp.0007_add_bar is not reversible

I guess there are several migrations which are not reversible ...

2 个答案:

答案 0 :(得分:10)

First: Remove references in the code

  • remove app_to_remove from settings.INSTALLED_APPS
  • remove other references in urls.py or other places

Second: Clean the database

Create an empty migration for your django-project:

manage.py makemigrations your_django_project --empty

Edit the file. Here is a template:

# -*- 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 the migration, run tests.

About "drop if exists": You have two cases:

  1. The production system: You want to drop the tables.
  2. New development systems: These systems never had this app, and they don't have this table :-)

答案 1 :(得分:0)

注意:本指南在Django 3.1.1和Python 3.8.2上是成功的

您可以尝试使用此解决方案先清理数据库并进行迁移

第1步:从文件your_app / models.py中删除表格,但保留文件本身

第2步:检查您是否在文件admin.py中注册了

步骤3:创建迁移:

manage.py makemigrations your_app

步骤4:迁移到数据库:

manage.py migrate

您可以在我的示例中看到结果 enter image description here

第5步:删除文件夹your_app / migrations中的所有文件

步骤6:删除表django_migrations中的迁移

python manage.py migrate --fake your_app zero

检查迁移:

python manage.py showmigrations

步骤7:然后,您可以完全删除该应用,检查引用INSTALLED_APPS