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 admin.py, views and etc.
- Remove the model from models.py
- 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:
- Register permissions in the admin, you can do it from any admin.py app file:
from django.contrib import admin
from django.contrib.auth.models import Permission
Now if you are superuser you can delete any permission.
- From Django Python Shell:
python manage.py shell
>>>from django.contrib.auth.models import Permission
>>>permissions = Permission.objects.all()
>>>for permission in permissions:
>>> print(permission, permission.pk) // 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 admin.py after finish the job.
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.)