April 29, 2025

Matching auto-imports in Django 5.2 to django-extensions

A quick one today! In Django 5.2 we have an awesome new feature of auto-imports into the shell. This has existed in django-extensions for as long as I can remember, but it's now in Django by default. That said the Django version only auto-imports your models and nothing else.

To customise what gets auto imported then you need to override the management command by creating a file in your project somewhere with the path management/commands/shell.py and then override get_auto_imports

Below is snippet to mirror the imports from shell_plus in django-extensions, just copy/paste and you no longer need to use shell_plus!

from django.core.management.commands import shell


class Command(shell.Command):
    def get_auto_imports(self):
        return super().get_auto_imports() + [
            "django.core.cache.cache",
            "django.conf.settings",
            "django.contrib.auth.get_user_model",
            "django.db.transaction",
            "django.db.models.Avg",
            "django.db.models.Case",
            "django.db.models.Count",
            "django.db.models.F",
            "django.db.models.Max",
            "django.db.models.Min",
            "django.db.models.Prefetch",
            "django.db.models.Q",
            "django.db.models.Sum",
            "django.db.models.When",
            "django.utils.timezone",
            "django.urls.reverse",
            "django.db.models.Exists",
            "django.db.models.OuterRef",
            "django.db.models.Subquery",
        ]