Skip to content

Consider including a shell_plus type package or tool #36

Open

Description

🎯Aim

Have an easy way to start a shell with all the relevant models (and maybe other helpers) autoloaded.

📕Context

The django-extensions project provides a nice autoloading of models etc when using the shell_plus command. However, django-extensions also includes a whole grab-bag of other stuff we don't necessarily want to include.

There are potentially a couple of ways to do this.

One we have used previously is to include an ipython_config.py in the root of the project so a shell started there will autoload the models. The code (thanks @a-musing-moose ) is:

"""
An IPython config script to import settings and models

When IPython is installed Django will automatically use it when you ask for a `shell`. This little
ipython config script is loaded by IPython on startup and will import the Django settings and all
the registered models.

Warning: You will get errors if you try to run IPython directly as the Django framework will not
have been properly bootstrapped.
"""
c = get_config()  # noqa
c.InteractiveShellApp.exec_lines = [
    "from django.conf import settings",
    "print('\\nImported \u001b[32;1msettings\u001b[0m from \u001b[37;1mdjango.conf\u001b[0m')",
    "from django.apps import apps",
    "import itertools",
    "globals().update({m.__name__: m for m in apps.get_models()})",
    "print(\"\\n\".join(['Imported \u001b[32;1m' + ', '.join([m.__name__ for m in g]) + f'\u001b[0m from \u001b[37;1m{k}\u001b[0m' for k, g in itertools.groupby(sorted(apps.get_models(), key=lambda m: m._meta.app_label), key=lambda m: m._meta.app_label)]))",
]

We could potentially approximately duplicate the functionality of the shell_plus part of django-extensions (but rewritten in such a way as to ensure no licensing problems).

Or we could just include django-extensions as a dev-only requirement (but we'd want to make sure we test without it!)

📝Relevant resources/doc's/people

Slack thread where django-extensions came up (although it was talking more about generating a graph of the model relationships): https://ackama.slack.com/archives/CV0H0QML7/p1709941586747639
Django extensions itself: https://django-extensions.readthedocs.io/en/latest/

✅Acceptance Criteria

  • A Django shell can easily be started with models already imported and ready for use (and possibly some other helper libraries?)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions