w3resource

Integrate PostgreSQL with Django: Complete Setup and Usage Guide


PostgreSQL with Django: Setup and Usage Guide

Django, a high-level Python web framework, makes it easy to build secure and scalable applications, while PostgreSQL serves as a powerful, reliable relational database for handling complex data structures. Integrating PostgreSQL with Django provides a robust, flexible environment for web development. This guide will walk you through setting up and using PostgreSQL as the backend database for your Django project, covering configuration, models, migrations, and basic queries.

Step 1: Install Required Packages

First, ensure both Django and the PostgreSQL adapter for Python (psycopg2) are installed:

pip install django psycopg2

Step 2: Configure Django to Use PostgreSQL

In your Django project’s settings file (settings.py), update the DATABASES setting to configure PostgreSQL as the database.

Code:

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',  # Specify PostgreSQL as the database
        'NAME': 'your_db_name',                     # Name of your PostgreSQL database
        'USER': 'your_db_user',                     # PostgreSQL username
        'PASSWORD': 'your_password',                # PostgreSQL password
        'HOST': 'localhost',                        # Database server address
        'PORT': '5432',                             # Default PostgreSQL port
    }
}

Step 3: Create Models for Your Django App

Create a model that Django will use to generate tables in PostgreSQL.

Code:


# models.py in your Django app
from django.db import models
# Define a simple model for a 'Customer' table
class Customer(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

Step 4: Run Migrations to Create Tables in PostgreSQL

Django uses migrations to apply model changes to the database schema. Run the following commands to create and apply migrations.

Code:


# Generate migration files based on models
python manage.py makemigrations

# Apply migrations to the database
python manage.py migrate

Step 5: Using Django’s ORM to Interact with PostgreSQL

With your models set up and migrated, you can interact with PostgreSQL through Django’s ORM.

Insert Data

Code:


# Insert a new customer record
from yourapp.models import Customer

new_customer = Customer(first_name=" Kris ", last_name="Taaniel", email="[email protected]")
new_customer.save()

Query Data

Code:

# Retrieve all customers
customers = Customer.objects.all()
for customer in customers:
    print(customer.first_name, customer.last_name)

Filter Data

Code:


# Filter customers by email
customer = Customer.objects.filter(email="[email protected]").first()
print(customer)

Explanation of Code:

  • Installation: pip install django psycopg2 installs Django and the PostgreSQL adapter.
  • Configuration: The DATABASES setting in settings.py configures Django to use PostgreSQL with specific credentials and database details.
  • Model Definition: The Customer model maps to a PostgreSQL table, where fields are defined as columns.
  • Migration: makemigrations creates migration files based on models, and migrate applies these changes, creating the necessary PostgreSQL tables.
  • Data Operations: Basic CRUD operations—like save(), all(), and filter()—are supported by Django’s ORM, making database management simple and efficient.

Additional Tips:

  • Database Indexing: Use Django’s Meta class within models to set up indexing, which can improve query performance on frequently accessed columns.
  • Django Admin: Once configured, PostgreSQL tables are easily managed via Django’s built-in admin interface.
  • Transactions: Django’s ORM handles database transactions automatically, ensuring data integrity.

All PostgreSQL Questions, Answers, and Code Snippets Collection.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/PostgreSQL/snippets/postgresql-django-integration.php