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

标签 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

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

最佳答案

首先:删除代码中的引用

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

第二:清理数据库

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

manage.py makemigrations your_django_project --empty

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

# -*- 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 table if exists app_to_remove_table1;
        drop table if exists 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 django_content_type where app_label = '{app_label}';
        delete from django_migrations where app='{app_label}';
        '''.format(app_label='app_to_remove'))
    ]

运行迁移,运行测试。

关于“如果存在则丢弃”:你有两种情况:

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

关于python - 如何从 Django 项目(及其所有表)中删除应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745220/

相关文章:

ios - Realm 迁移 : Why in documentation it is recommended to call the migration block each time without checking the schema version before?

database - Laravel 迁移是否应该用于更改实时列值?

python - pandas 在不同大小的 2 个表(1 个聚合表)之间执行划分

python - 如何避免使用过多的 if else ?

python - 当我们有 20 到 50 列时,如何在 Pandas 中创建 3 列或 4 列的 Dataframe 列表?

python - 使用 S3 子文件夹作为 Django 收集静态目标

database-migration - 可重复迁移的飞路和初始化

python - Flask:添加使用统计

Django 多个缓存后端路由器如何?

python - 如何将组添加到模型的每个实例