Does Django have an equivlant to ruby on rails "rails db:create"?

Viewed 38

I've been searching on google about this but everyone is saying Django lacks this feature. I should not have to manually create the initial database in PGAdmin or something similar just to start development. What is the django equivalent of rails db:create?

Operational Error: FATAL: database "django" does not exist

This link above is not an answer. I should not have to load up PgAdmin just to create an initial database.

1 Answers

I ended up just creating a custom command.

import psycopg2
from django.core.management.base import BaseCommand

from ugh_studios_webservices import settings


class Command(BaseCommand):
    help = 'Create the initial database with the name set in settings.py'

    def handle(self, *args, **options):
        db_type = settings.DATABASES['default']['ENGINE']
        if db_type != 'django.db.backends.postgresql':
            print('This command is only currently setup to support postgresql databases.')
            return

        default_db = settings.DATABASES['default']
        db_name = default_db['NAME']
        db_username = default_db['USER']
        db_password = default_db['PASSWORD']
        db_host = default_db['HOST']
        db_port = default_db['PORT']
        connection = psycopg2.connect(host=db_host, database='postgres', user=db_username, password=db_password,
                                      port=db_port)
        connection.set_isolation_level(0)
        cursor = connection.cursor()
        cursor.execute(f'CREATE DATABASE {db_name}')
        connection.commit()
        cursor.close()
        connection.close()
Related