Ghopper21
Ghopper21

Reputation: 10477

If multiple Django apps define the same custom management command, which is used?

The docs are silent on this questios. Will the commands be registered in order, with later apps (in settings.INSTALLED_APPS order) overriding previous commands (whether custom from other apps or the built-in Django commands)?

Upvotes: 6

Views: 2221

Answers (3)

smilingwang
smilingwang

Reputation: 119

From Django 2.2 official documentation

When several applications provide different versions of the same resource (template, static file, management command, translation), the application listed first in INSTALLED_APPS has precedence.

Upvotes: 1

benjyw
benjyw

Reputation: 21

Commands are registered in reverse app order (see here). So to override FooCommand in app foo with your own version in app bar, bar must precede foo in settings.INSTALLED_APPS.

This is unfortunate, because you may need bar to follow foo for other reasons. E.g., if bar's models reference foo's models.

One solution is to split the overriding command out into a separate app, if feasible.

Upvotes: 1

Ghopper21
Ghopper21

Reputation: 10477

The answer is yes, as of the current 1.7 release.

See this line in the Django source to see where the logic is implemented: in the order of apps per the settings.INSTALLED_APPS tuple, each app's management commands are added to a dictionary of commands (which was initialized with Django's built-in commands here), with a single slot for any given command name, so that last one added sticks, overriding any previous app's (or Django's built-in) command with the same name; when executing a command (code here), Django uses the dictionary above to decide which command logic to actually use.

Note I haven't found any documentation of this, so it should technically be considered unofficial behavior.

Upvotes: 5

Related Questions