Search code examples
djangocommandmultiple-databases

How can I call a custom Django manage.py command directly from code with specific database connection


I followed this solution to run customer Django command programmatically, but it is limited for just one database connection.

I have Django app configured with multiple database , is it possible to run custom Django command using specific database connection?

exactly like when we use connections["DB_NAME_CONNECTION"].cursor() to execute an sql query.


Solution

  • One option is to create a new settings module (here's a guide) that contains your specific database connection configuration, and then use that settings module when using call_command():

    management.call_command('mycommand', '--settings=mysite.settings.specificconnection')