Last active
October 30, 2022 10:18
-
-
Save mjnaderi/c17988d717f6fd0c9f46d98580af95c3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.auth.models import Permission | |
from django.db.models.deletion import ProtectedError | |
from django.contrib.contenttypes.models import ContentType | |
from django.db.models.deletion import Collector | |
def get_dependencies(obj): | |
collector = Collector(using="default") | |
collector.collect([obj]) | |
return collector.data | |
def permission_is_used(permission): | |
try: | |
dependencies = get_dependencies(permission) | |
except ProtectedError: | |
return True | |
if len(dependencies) != 1: | |
return True | |
if Permission not in dependencies: | |
return True | |
return False | |
def content_type_is_used(content_type): | |
if content_type.model_class(): | |
return True | |
try: | |
dependencies = get_dependencies(content_type) | |
except ProtectedError: | |
return True | |
dependencies.pop(ContentType) | |
try: | |
permissions = dependencies.pop(Permission) | |
for perm in permissions: | |
if permission_is_used(perm): | |
return True | |
except KeyError: | |
pass | |
if len(dependencies) > 0: | |
return True | |
return False | |
unused_content_type_ids = [] | |
for content_type in ContentType.objects.all().order_by("app_label", "model"): | |
if not content_type_is_used(content_type): | |
print(content_type.id, content_type.app_label, content_type.name, content_type.model, content_type.model_class()) | |
unused_content_type_ids.append(content_type.id) | |
# Run this if you are sure about everything: | |
# ContentType.objects.filter(id__in=unused_content_type_ids).delete() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment