Django connects to an external database through a database connection defined in the project’s settings.py file. The DATABASES setting in settings.py defines the database connection parameters, including the database type, the name of the database, the username and password for connecting to the database, and other parameters such as the host, port, and charset.
Here’s an example of a DATABASES setting for a PostgreSQL database:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } }
In this example, the ENGINE setting specifies the database type (postgresql), the NAME setting specifies the name of the database (mydatabase), and the USER and PASSWORD settings specify the username and password for connecting to the database. The HOST and PORT settings specify the host and port of the database server.
Once the database connection is defined in the settings.py file, you can use Django’s ORM to interact with the database, including querying data, inserting data, updating data, and deleting data.