2

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.

Ryan Glenn
  • 1,325
  • 4
  • 17
  • 30
  • "I should not have to load up PgAdmin just to create an initial database"—"Well, that's just, like, your opinion, man..." Django and Rails do certain things differently. Neither is inherently right or wrong. – ChrisGPT was on strike Feb 27 '22 at 20:44
  • I fixed the problem in my answer below. I hope this command could get added to future versions of Django. – Ryan Glenn Feb 27 '22 at 20:48

1 Answers1

1

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()
Ryan Glenn
  • 1,325
  • 4
  • 17
  • 30