How to correctly remove a Model or an App in Django

When you remove a Django Model or a full app in Django, you have to be careful in how you do it, and how the database will be affected.

Thus, in this short post I’ll explain what I do when deleting a model or an app.

Remove the Models from models.py

Weather you’re removing a single model or a full app, you should first remove the desired models from the models.py file.

Moreover, you have to make sure that no other file imports these models or uses them (admin.py, views.py, etc).

Next, run South or migrate your database to properly delete these models from your database.

If you are using South, you should run something like

changing your-app by the name of the app to migrate (where your deleted models were).

Remove an App from your Django project

Next, if you are removing an entire app, you can now remove all the files in that app (models.py, views.py, etc). Again, make sure that the other apps don’t make an import from these files.

And finally, remove this app from your Installed Apps in the settings.py file.

Remove the remnant ContentTypes

But after doing all this, you will still have remnants of your models in the ContentType table, like permissions related to the deleted models.

One way to see this is when creating a Group in the Auth app using the admin. When you have to choose the permissions of the group, the box will show permissions that refer to the deleted models.

To clean these tables, we will create the file clean_model_app_remove.py and write the following:

where you should write in DEL_APPS the apps that you deleted, and in DEL_MODELS the models that you delete and that do not belong to any of the deleted apps. Moreover, note that the models have to be written in lowercase.

Finally, we just need to run our script with

Great! Now we cleanly removed our apps/models! 🙂

Google+TwitterLinkedInFacebookReddit

Please, add +Marina Mele in your comments. This way I will get a notification email and I will answer you as soon as possible! :-)