[Django]-Automatically import all db tables in manage.py shell

7👍

django-extensions adds the shell_plus command for manage.py which does exactly this.

1👍

from django.db.models import get_models
for _class in get_models():
    globals()[_class.__name__] = _class

Here you end up with all installed models available globally, refering to them with their class name. Read the docs for django.db.models.get_models for more info:

Definition: get_models(self, app_mod=None, include_auto_created=False, include_deferred=False)
Docstring:
Given a module containing models, returns a list of the models.
Otherwise returns a list of all installed models.

By default, auto-created models (i.e., m2m models without an
explicit intermediate table) are not included. However, if you
specify include_auto_created=True, they will be.

By default, models created to satisfy deferred attribute
queries are not included in the list of models. However, if
you specify include_deferred, they will be.

0👍

You can do this:

>>> from django.conf import settings
>>> for app in settings.INSTALLED_APPS:
...   module = __import__(app)
...   globals()[module.__name__] = module
...

You’ll get the fully qualified names though; userprofile.models.Table instead of Table.

Leave a comment