Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 686
Julio Marins Avatar asked Nov 26 '18 19:11

Julio Marins


People also ask

How do I delete an existing model in Django?

Now doing “python manage.py migrate” will migrate the old models data and its relations to the new one. Then do “makemigrations” and “migrate”! That's it. You have successfully removed a Django model and its relations without introducing any errors in your project.

How does Django store data in database?

To create an object, instantiate it using keyword arguments to the model class, then call save() to save it to the database. This performs an INSERT SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() . The save() method has no return value.

What to do after creating models in Django?

Once you have defined your models, you need to tell Django you're going to use those models. Do this by editing your settings file and changing the INSTALLED_APPS setting to add the name of the module that contains your models.py .

How would you stop Django from performing database table creation?

From the documentation: If False, no database table creation or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means.


1 Answers

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},
        ),
    ]
like image 131
n8sty Avatar answered Oct 25 '22 21:10

n8sty