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.

2
  • "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. Commented Feb 27, 2022 at 20:44
  • I fixed the problem in my answer below. I hope this command could get added to future versions of Django. Commented Feb 27, 2022 at 20:48

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.