4

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

1 Answer 1

10

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

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.