开发者

Automatically import all db tables in manage.py shell

开发者 https://www.devze.com 2023-04-01 02:24 出处:网络
Is there a snippet or easy way to impo开发者_运维技巧rt all of my django tables when entering the prompt?

Is there a snippet or easy way to impo开发者_运维技巧rt all of my django tables when entering the prompt?

For example, usually my commands go something like this:

>>> from userprofile.models import Table
>>> Table.objects...

This way, as soon as I entered the prompt, I'd already have the tables imported. Thank you.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消