When building web applications with Python, the Django framework plays a crucial role. By default, Django applications store data in a lightweight SQLite database. However, many developers prefer PostgreSQL over SQLite due to its advanced features and ability to handle complex databases more effectively.
PostgreSQL offers robust capabilities that can significantly boost production performance when integrated with Django. If you’re looking to configure a PostgreSQL database for your Django application, you’re in the right place! This guide walks you through the steps to seamlessly connect PostgreSQL to Django and optimize your application.
How to Establish Django PostgreSQL Connection?
Now that you have a clear vision of the benefits in your mind, let’s walk past the steps required to establish the Django PostgreSQL connection. But first, let’s state some prerequisites.
Step 1: Creating and Activating Virtual Environment
Open your Command Line Interface(CLI) and create a project directory using the following command.
mkdir django-postgres
After creating the directory, the next step is to point towards the created directory with the following command.
cd django-postgres
In the Project development phase creating a virtual environment is a good practice. You can control the environment by segregating its environment from the rest of the systems.
The command to create a virtual environment is as follows:
python -m venv env;
The final step is to activate the virtual environment by running the command given below.
env/scripts/activate
Step 2: Installing Django and PostgreSQL
Now you have created a virtual environment for your project, so it’s time to install the required dependencies i.e., Django and PostgreSQL.
pip install django
The above command will install the latest version of Django to your project.
Install the “psycopg2” module to get Python to operate with Postgres.
pip install psycopg2
Are you looking for an ETL tool to migrate your PostgreSQL data? Migrating your data can become seamless with Hevo’s no-code intuitive platform. With Hevo, you can:
- Automate Data Extraction: Effortlessly pull data from various sources and destinations with 150+ pre-built connectors.
- Transform Data effortlessly: Use Hevo’s drag-and-drop feature to transform data with just a few clicks.
- Seamless Data Loading: Quickly load your transformed data into your desired destinations, such as BigQuery.
- Transparent Pricing: Hevo offers transparent pricing with no hidden fees, allowing you to budget effectively while scaling your data integration needs.
Try Hevo and join a growing community of 2000+ data professionals who rely on us for seamless and efficient migrations.
Get Started with Hevo for Free
Step 3: Creating Application in Django
Let’s create our first project, which will only have one project in our project directory but will let us add as many applications as we need.
django-admin startproject postgresTest
As a result of the above command, the “postgreTest” project folder will be generated in your project directory. You can verify the same in Visual Studio Editor.
Open up the project directory in Visual Studio and activate the virtual environment. Open the Visual Studio terminal and move to the project directory using the following command.
cd postgresTest
python manage.py startapp testdb
To launch your first app, use the following command.
Note: Don’t forget to mention your newly created application in the INSTALLED_APPS list in the settings.py file.
Kudos to you for creating your first application in Django!
Now, try running the server to ensure that everything is working correctly. Run the following command in the visual studio terminal.
python manage.py runserver
If everything is working correctly, you will get a link where your application is hosted on the local server. After clicking that link, you will land on the webpage shown below.
Step 4: Configuring Django Application Settings
Create a database named “test” in your Postgres server using pgAdmin4.
It is now time to switch from the default database connection, i.e., SQLite3, to PostgreSQL in your Django project.
- Go to the settings.py file.
By default, you will find the lines of code that are shown below. This code is configuring Django with the default database(SQLite3).
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
You need to change the above settings to the parameters as shown below:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': ‘<database_name>’,
'USER': '<database_username>',
'PASSWORD': '<password>',
'HOST': '<database_hostname_or_ip>',
'PORT': '<database_port>',
}
}
Step 5: Testing Connection
Run the following command to migrate all tables in our Django project to PostgreSQL.
python manage.py makemigrations
python manage.py migrate
You will get the output as shown below.
Congratulations!! You’ve successfully established the Django PostgreSQL connection.
Why is Django PostgreSQL Connection Useful?
The primary reasons to use Django PostgreSQL integration are mentioned below:
- Django includes a variety of data types that are exclusively compatible with PostgreSQL.
- Django provides django.contrib.postgres for PostgreSQL database operations.
- If you are creating a map-based application or storing geographical data, you must utilize PostgreSQL since it works with GeoDjango.
- Django supports the most functionality in PostgreSQL.
- Django offers crucial PostgreSQL-specific features such as aggregation functions, database constraints, form fields widgets, lookups, full-text search, Validators, and more.
We’ve seen how Django is the most capable web framework, and PostgreSQL is the most robust and dependable RDBMS. As a developer, you can leverage the versatility of PostgreSQL to work with almost any type of data and the unbeatable features of Django to develop fast and secure web applications.
Conclusion
In this guide, you have learned about PostgreSQL and Django briefly, their key features respectively, benefits of establishing a Django PostgreSQL connection. Moreover, you now have a detailed understanding of how to use PostgreSQL with your Django application.
Hopefully, you will try leveraging the Django PostgreSQL connection for your future web applications. Feel free to leave a comment below expressing your thoughts or recommendations.
If you use PostgreSQL, copying data into a warehouse using ETL scripts can be time-consuming. And the fact that organizations require significant funds to recruit data engineers to maintain those scripts only exaggerates the problem. Here is where Hevo Data can help you.
With integration with 150+ Data Sources (60+ free sources), Hevo helps you not only export data from sources & load data to the destinations but also transform & enrich your data, & make it analysis-ready.
Give Hevo a try. SIGN UP for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at the unbeatable pricing that will help you choose the right plan for your business needs.
Share your thoughts on learning about Django PostgreSQL in the comments section below. If you have any questions, do let us know. We’d be happy to help.
FAQs
1. Is PostgreSQL good for Django?
Yes, PostgreSQL is an excellent choice for Django. It offers advanced features like full-text search, JSON support, and scalability, making it ideal for handling complex applications. Django’s built-in support for PostgreSQL allows developers to leverage these features seamlessly.
2. How to PostgreSQL with Django?
To use PostgreSQL with Django, install the psycopg2
library, which acts as the PostgreSQL adapter for Python. Update the DATABASES
setting in your Django settings.py
file to configure PostgreSQL with the required credentials like database name, user, password, host, and port. Then, run migrations to apply changes.
3. Which database is best for Django?
The best database for Django depends on your project’s requirements. PostgreSQL is highly recommended due to its advanced features, scalability, and compatibility with Django’s ORM. However, SQLite is suitable for lightweight projects, while MySQL and MariaDB work well for applications needing high performance and broad support.
4. How to connect PostgreSQL database in Django rest framework?
To connect a PostgreSQL database in Django Rest Framework, update the DATABASES
setting in your settings.py
file with PostgreSQL credentials, including ENGINE
as 'django.db.backends.postgresql'
. Install psycopg2
as the database adapter, and then run migrations using python manage.py migrate
to set up the database schema.
Kamya is a dedicated data science enthusiast who loves crafting comprehensive content that tackles the complexities of data integration. She excels in SEO and content optimization, collaborating closely with SEO managers to enhance blog performance at Hevo Data. Kamya's expertise in research analysis allows her to produce high-quality, engaging content that resonates with data professionals worldwide.