Prateek Jain
Prateek Jain

Reputation: 196

How can I connect my existing external PostgreSQL Database to automatically create my Models.py for a Django Rest Framework?

I have an existing PostgreSQL Database and I want to create APIs around it using Django Rest Framework. How do I display the tables in my Database as models in Django to further use them for the API?

Upvotes: 3

Views: 1179

Answers (1)

Panos Angelopoulos
Panos Angelopoulos

Reputation: 609

First of all, you have to connect the existing DB with your Django application by following those instructions https://docs.djangoproject.com/en/3.1/ref/databases/#postgresql-notes or simply add the code below in your settings.py file

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db_name',                      
        'USER': 'db_user',
        'PASSWORD': 'db_user_password',
        'HOST': '',
        'PORT': 'db_port_number',
    }
}

Secondly, Django provides a powerful command which will help you out to inspect your existing DB models and save those models into your models.py file.

python manage.py inspectdb > models.py

In case that you need more information please read the official documentation https://docs.djangoproject.com/en/3.1/howto/legacy-databases/#auto-generate-the-models.

Upvotes: 4

Related Questions