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

前端 未结 7 1737
挽巷
挽巷 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:36

    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.

提交回复
热议问题