Julio Marins
Julio Marins

Reputation: 10639

How do I remove a model but keep the database table on Django

I want to remove the class declaration of the model but want to keep the records and the table on the database. How can I do that?

Upvotes: 11

Views: 3569

Answers (2)

n8sty
n8sty

Reputation: 1438

Stop Django managing your model by setting the Meta class attribute managed to False (default is True) like in the following:

class SomeModel(models.Model):
    ....

    class Meta:
        managed = False

Then run python manage.py makemigrations, which should create a migration telling you something like

- Change Meta options on something

Run that migration by python manage.py migrate, which will stop Django from managing that model and then delete it from your code base. The migration will look like:

class Migration(migrations.Migration):

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

    operations = [
        migrations.AlterModelOptions(
            name='something',
            options={'managed': False},
        ),
    ]

Upvotes: 16

grouchoboy
grouchoboy

Reputation: 1024

If the class it not going to be used anywhere but you want to keep the data:

  • Do a dump of that data and create a new database to store the dump data.
  • Delete the model.
  • Make a migration deleting the model.

If you delete the model in the code I think that always you execute a manage makemigrations it will create a migration to delete the table.

Upvotes: -2

Related Questions