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
$ python manage.py schemamigration --auto your-app $ python manage.py migrate your-app
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:
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()
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
$ python manage.py shell >>>execfile("clean_model_app_remove.py")
Great! Now we cleanly removed our apps/models! 🙂
Marina Mele has experience in artificial intelligence implementation and has led tech teams for over a decade. On her personal blog (marinamele.com), she writes about personal growth, family values, AI, and other topics she’s passionate about. Marina also publishes a weekly AI newsletter featuring the latest advancements and innovations in the field (marinamele.substack.com)