在Django中,是否可以找到ORM知道的模型列表或查找模型?
Answers:
简单的解决方案:
import django.apps
django.apps.apps.get_models()
默认情况下apps.get_models()
不包括
如果您也要包括这些内容,
django.apps.apps.get_models(include_auto_created=True, include_swapped=True)
在Django 1.7之前,请改用:
from django.db import models
models.get_models(include_auto_created=True)
该include_auto_created
参数确保ManyToManyField
s隐式创建的表也将被检索。
from django.apps.apps import get_models
产生ImportError: No module named 'django.apps.apps'
...任何想法?
from django.apps import apps
>>apps.get_models
使用http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/列出模型
from django.contrib.contenttypes.models import ContentType
for ct in ContentType.objects.all():
m = ct.model_class()
print "%s.%s\t%d" % (m.__module__, m.__name__, m._default_manager.count())
如果您想玩,而不是使用好的解决方案,则可以使用python introspection玩一点:
import settings
from django.db import models
for app in settings.INSTALLED_APPS:
models_name = app + ".models"
try:
models_module = __import__(models_name, fromlist=["models"])
attributes = dir(models_module)
for attr in attributes:
try:
attrib = models_module.__getattribute__(attr)
if issubclass(attrib, models.Model) and attrib.__module__== models_name:
print "%s.%s" % (models_name, attr)
except TypeError, e:
pass
except ImportError, e:
pass
注意:这是一段很粗糙的代码;它将假定所有模型都在“ models.py”中定义,并且它们都继承自django.db.models.Model。
这是查找和删除数据库中存在但ORM模型定义中不存在的任何权限的简单方法:
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))