Pycharm - autoload models in Django console

2019-02-24 20:43发布

问题:

Is there a way to autoload models in the pycharm django console (in a similar way to how django-extensions shell_plus works)?

回答1:

In pycharm setting, django console settings you can have a starting script:

This will automatically load the django models, like shell_plus:

import sys
import django
django.setup()

from django.apps import apps

for _class in apps.get_models():
    globals()[_class.__name__] = _class


回答2:

To extend Yunti's answer, if you want the models to be namespaced inside a 'models' module, you can create a module on-the-fly in the run script and add all models to it:

import sys
sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS])

import django 
django.setup()

import types
from django.apps import apps

models = types.ModuleType('models')
for _class in apps.get_models():
    setattr(ext_models, _class.__name__, _class)

To go even further, if you're working on a specific django app and want external models to be in a separate namespace than the models of your app, you can extend this even further:

import sys
sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS])

import django 
django.setup()

import types
from django.apps import apps
from your_project.your_app import models as your_models  # and views and tests and all the modules you want to import :)

ext_models = types.ModuleType('ext_models')
for _class in apps.get_models():
    _class_name = _class.__name__
    if not hasattr(your_models, _class_name):
        setattr(ext_models, _class_name, _class)

Now, all your models are available under your_models. and all external models (like AccessToken, Group, &c.) are available under ext_models.