[Django]-How to integrate django with existing Postgres database

6👍

Edit settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': '<name>',
        'USER': '<user>',
        'PASSWORD': '<password>',
        'HOST': '<host>',
        'PORT': '<port>',
    }
}

Generate models for linked existing database tables.

python manage.py inspectdb > models.py

Tweak your tables according to your preferences. Copy all tables and add them to your app models.py

Now create initial migrations for existing tables

python manage.py makemigrations

Run the migrate command to apply the migrations, Use –fake-initial option that applies the migrations where it’s possible and skips the migrations where the tables are already there:

python manage.py migrate --fake-initial

At this point, any new changes to the model structure and subsequent migrations would work as if Django managed the database since its inception

Thanks to: Dima Knivets

Leave a comment