How to delete models properly?

In my project, I have deleted some models in several apps.

To do this my road-map was like so,

  • Clean existing data for desired model.
  • Remove all relations from other models.
  • Remove all imports or uses from, views and etc.
  • Remove the model from
  • Make migrations and migrate for related app.

There is no problem about in any steps.

But when I checked permissions from admin panel, there is still written the permissions for deleted models.

I’ve read that it is due to ContentTypes. According that, there is still remains in there.

How can I do the deletion safely and correctly?
If I don’t make anything, will this cause problems in the future?

If you are absolutely sure you won’t use the permissions you can delete them in two ways:

  1. Register permissions in the admin, you can do it from any app file:
from django.contrib import admin
from django.contrib.auth.models import Permission

Now if you are superuser you can delete any permission.

  1. From Django Python Shell:
python shell

>>>from django.contrib.auth.models import Permission
>>>permissions = Permission.objects.all()
>>>for permission in permissions:
>>>    print(permission, // you get the natural key and pk of all permissions
>>> ...
>>>permission1 = Permission.objects.get(pk=x) // x is the pk of the permission you want do delete

I recommend the second one approach or to delete the Permission register of after finish the job.

1 Like

First, you don’t need to specifically delete the permissions - the permission model has a ForeignKey to ContentType with CASCADE. Delete the ContentType and the permissions go away.

To clean up old ContentType entries, see remove_stale_contenttypes.

So, run remove_stale_contenttypes and it’ll clean up most of those remaining issues.
(Caution, if you have Generic Foreign Keys, you can create problems doing this.)

1 Like