Get the ORM that is created by Django

From the Django docs:

How are the backward relationships possible?

Other object-relational mappers require you to define relationships on both sides. The Django developers believe this is a violation of the DRY (Don't Repeat Yourself) principle, so Django only requires you to define the relationship on one end.

But how is this possible, given that a model class doesn't know which other model classes are related to it until those other model classes are loaded?

The answer lies in the INSTALLED_APPS setting. The first time any model is loaded, Django iterates over every model in INSTALLED_APPS and creates the backward relationships in memory as needed. Essentially, one of the functions of INSTALLED_APPS is to tell Django the entire model domain.

Is there a way to get this ORM model? I am trying to debug some reverse relations that are not automagically created and it would really help to see the whole ORM Django has created.


There is no specific ORM "Model", however there are a few things that may help you.

from django.db.models.loading import get_models

get_models() will return you a list of every registered model, this list is what the mechanism that you are describing loops over.

YourModel._meta.get_all_related_objects_with_model()

This function loops over every field in every registered model and finds and returns any reverse relations to your YourModel .

The Options class from django.db.models.options ( YourModel._meta is an Options object) is a good place to look around for this stuff.


Django doesn't "create" an ORM so the question makes no sense. If you want to know what properties the ORM adds to your model classes to support backward relationships then you can

  • open a django shell, import your models and inspect them
  • read the source code (hey, it's open source isn't it ?)
  • if that's not enough, add breakpoints at appropriate places and run the whole thing thru the debugger
  • 链接地址: http://www.djcxy.com/p/60210.html

    上一篇: Django的对象组成与OneToOneField

    下一篇: 获取由Django创建的ORM