简体   繁体   中英

How to integrate django with existing Postgres database

To use an existing database in Django, you need to have a model for each table. But creating models for existing tables manually is just too much work. However, there's no need to do that, since Django has a builtin tool to solve this exact problem.

Reference article linked here: how-to-integrate-django-with-existing-database

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM