Django : How can I find a list of models that the ORM knows?

前端 未结 7 1731
挽巷
挽巷 2020-12-04 08:48

In Django, is there a place I can get a list of or look up the models that the ORM knows about?

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 09:35

    Here's a simple way to find and delete any permissions that exist in the database but don't exist in the ORM model definitions:

    from django.apps import apps
    from django.contrib.auth.management import _get_all_permissions
    from django.contrib.auth.models import Permission
    from django.core.management.base import BaseCommand
    
    
    class Command(BaseCommand):
        def handle(self, *args, **options):
            builtins = []
            for klass in apps.get_models():
                for perm in _get_all_permissions(klass._meta):
                    builtins.append(perm[0])
            builtins = set(builtins)
    
            permissions = set(Permission.objects.all().values_list('codename', flat=True))
            to_remove = permissions - builtins
            res = Permission.objects.filter(codename__in=to_remove).delete()
            self.stdout.write('Deleted records: ' + str(res))
    

提交回复
热议问题