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

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

Posted by: admin November 30, 2017 Leave a comment

Questions:

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

Answers:

Simple solution:

import django.apps
django.apps.apps.get_models()

Prior to Django 1.7, instead use:

from django.db import models
models.get_models(include_auto_created=True)

The include_auto_created parameter ensures that through tables implicitly created by ManyToManyFields will be retrieved as well.

Questions:
Answers:

List models using 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())

Questions:
Answers:

If you want to play, and not use the good solution, you can play a bit with 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

Note: this is quite a rough piece of code; it will assume that all models are defined in “models.py” and that they inherit from django.db.models.Model.

Questions:
Answers:

If you use the contenttypes app, then it is straightforward: http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/

Questions:
Answers:

If you register your models with the admin app, you can see all the attributes of these classes in the admin documentation.