views:

209

answers:

4

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

+1  A: 

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

dar
A: 

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.

Roberto Liffredo
+11  A: 

Simple solution:

from django.db import models
models.get_models()

will give you a list of all the model classes that have been loaded.

Daniel Roseman
A: 

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

Technical Bard