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
1 2 |
$ python manage.py schemamigration --auto your-app $ python manage.py migrate your-app |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
from django.contrib.contenttypes.models import ContentType # List of deleted apps DEL_APPS = ["app-you-deleted", "second-app-deleted"] # List of deleted models (that are not in the app deleted) In lowercase! DEL_MODELS = ["model-you-deleted", "second-model-deleted"] ct = ContentType.objects.all().order_by("app_label", "model") for c in ct: if (c.app_label in DEL_APPS) or (c.model in DEL_MODELS): print "Deleting Content Type %s %s" % (c.app_label, c.model) c.delete() |
Finally, we just need to run our script with
1 2 |
$ python manage.py shell >>>execfile("clean_model_app_remove.py") |
Great! Now we cleanly removed our apps/models! 🙂
Please, add +Marina Mele in your comments. This way I will get a notification email and I will answer you as soon as possible! :-)