How to create a mysql database in Django on the first run?

I'd like my application to be "plug-and-play", so I need to automatically create the database on the first run. I use docker with docker-compose

My attempt is to connect without specifying the database name and run a custom command before running the server:

  sh -c "python create_db &&
         python runserver"

And the command itself:

class Command(BaseCommand):
"""Django command to create DB"""

def handle(self, *args, **options):
    con = connections['default']
    db_name = os.environ.get('DB_NAME')
    db_up = False
    while not db_up:
            cursor = con.cursor()
            cursor.execute(f'CREATE DATABASE IF NOT EXISTS {db_name}')
            cursor.execute(f'USE {db_name}')
            db_up = True
        except Exception as err:
            self.stdout.write('Database unavailable, waiting 1 second...')
    self.stdout.write('Database available!'))

If this is the right way, then now I just need to update the connection to use the newly created database, but I don't know how. The line cursor.execute(f'USE {db_name}') of course doesn't work.

My questions are: Is it the right way to create the database? If so, how to update the connection? If not, how to do it?


This what my management command generally looks like

call_command() basically does python {command}

from import BaseCommand
from import call_command

class Command(BaseCommand):
    help = 'does thing'

    def add_arguments(self, parser):
        # Named (optional) arguments
            help='Skips Import',

    def handle(self, *args, **kwargs):
        print("Doing Thing")

        # create migrations
        call_command('makemigrations') # (Django Command)

        # can also pass arguemnts like a specific app
        # call_command('makemigrations', 'app1')

        # This create db **if** it doesn't exist
        #   + checks that migrations are up to date
        call_command('migrate') # (Django Command)

        if kwargs['import']:
            # another management command to handle importing
            #   I've just a csv reader and a loop
            call_command('importDb') # (Custom Command)

        # Collect Static (+ don't ask for confirmation)
        call_command('collectstatic', interactive=False) # (Django Command)

        print('Thing has been Done')

So with that, I just run:
python dothing (python dothing --import if I want db to be imported)
and then:
python runserver and it's good to go!


Just do something like this and pull the options from the settings:

Back to Top