Dan*_*man 159
简单方案:
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 隐式创建的表.
小智 10
使用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())
如果你想要一个包含所有模型的字典,你可以使用:
from django.apps import apps
models = {
    model.__name__: model for model in apps.get_models()
}
如果你想玩,并且不使用好的解决方案,你可以玩一下 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。
| 归档时间: | 
 | 
| 查看次数: | 24883 次 | 
| 最近记录: |