- Visit https://www.postgresql.org/download/windows/
- Click on "Download the installer"
- Download the latest version for Windows (x86-64)
- Double-click the downloaded
.exefile - Click "Next" on the welcome screen
- Choose installation directory (default:
C:\Program Files\PostgreSQL\16) - Select components to install:
- ✓ PostgreSQL Server
- ✓ pgAdmin 4
- ✓ Stack Builder
- ✓ Command Line Tools
- Choose data directory (default:
C:\Program Files\PostgreSQL\16\data) - Set password for postgres superuser (IMPORTANT: Remember this password!)
- Set port number (default:
5432) - Select locale (default:
[Default locale]) - Review installation summary and click "Next"
- Wait for installation to complete
- Uncheck "Stack Builder" and click "Finish"
- Open Command Prompt or PowerShell
- Run:
psql --version- You should see:
psql (PostgreSQL) 16.x
- Search "Environment Variables" in Windows
- Click "Environment Variables"
- Under "System variables", find "Path"
- Click "Edit" → "New"
- Add:
C:\Program Files\PostgreSQL\16\bin - Click "OK" on all windows
- Restart Command Prompt/PowerShell
psql -U postgresEnter the password you set during installation.
CREATE USER django_user WITH PASSWORD 'your_secure_password';ALTER ROLE django_user SET client_encoding TO 'utf8';
ALTER ROLE django_user SET default_transaction_isolation TO 'read committed';
ALTER ROLE django_user SET timezone TO 'UTC';
ALTER ROLE django_user CREATEDB;\duYou should see django_user in the list.
CREATE DATABASE django_db OWNER django_user;GRANT ALL PRIVILEGES ON DATABASE django_db TO django_user;\lYou should see django_db in the list.
\qpsql -U django_user -d django_dbEnter the password for django_user. If successful, you're connected!
# Windows
venv\Scripts\activate
# Linux/Mac
source venv/bin/activatepip install psycopg2-binarypip list | grep psycopg2Navigate to your Django project directory:
cd your_project_nameOpen your_project_name/settings.py
Find the DATABASES section and replace it with:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'django_db',
'USER': 'django_user',
'PASSWORD': 'your_secure_password',
'HOST': 'localhost',
'PORT': '5432',
}
}python manage.py check --database defaultIf no errors appear, the connection is successful!
python manage.py shellThen run:
from django.db import connection
connection.ensure_connection()
print("Database connection successful!")
exit()In your app's models.py (e.g., myapp/models.py):
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=10, decimal_places=2)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.namepython manage.py makemigrationsThis creates migration files based on your models.
python manage.py sqlmigrate myapp 0001python manage.py migrateThis creates all necessary tables in PostgreSQL.
python manage.py showmigrationsAll migrations should have [X] marks.
python manage.py createsuperuserFollow the prompts to set username, email, and password.
python manage.py shellfrom myapp.models import Product# Create single record
product1 = Product.objects.create(
name='Laptop',
price=999.99,
description='High-performance laptop'
)
# Create multiple records
Product.objects.bulk_create([
Product(name='Mouse', price=25.50, description='Wireless mouse'),
Product(name='Keyboard', price=75.00, description='Mechanical keyboard'),
])# Get all records
all_products = Product.objects.all()
for product in all_products:
print(f"{product.name}: ${product.price}")
# Filter records
expensive = Product.objects.filter(price__gt=50)
# Get single record
product = Product.objects.get(id=1)
print(product.name)
# Get first/last
first = Product.objects.first()
last = Product.objects.last()
# Count records
count = Product.objects.count()# Update single record
product = Product.objects.get(id=1)
product.price = 899.99
product.save()
# Update multiple records
Product.objects.filter(price__lt=30).update(price=29.99)# Delete single record
product = Product.objects.get(id=1)
product.delete()
# Delete multiple records
Product.objects.filter(price__lt=20).delete()
# Delete all records (use with caution!)
Product.objects.all().delete()# Order by
products = Product.objects.order_by('-price') # Descending
products = Product.objects.order_by('name') # Ascending
# Limit results
products = Product.objects.all()[:5] # First 5
# Exclude
products = Product.objects.exclude(price__lt=50)
# Complex queries
from django.db.models import Q
products = Product.objects.filter(
Q(price__lt=100) | Q(name__icontains='laptop')
)
# Aggregate
from django.db.models import Avg, Sum, Count
avg_price = Product.objects.aggregate(Avg('price'))
total = Product.objects.aggregate(Sum('price'))psql -U django_user -d django_db\dt\d myapp_product-- Select all records
SELECT * FROM myapp_product;
-- Select specific columns
SELECT id, name, price FROM myapp_product;
-- Filter records
SELECT * FROM myapp_product WHERE price > 50;
-- Order results
SELECT * FROM myapp_product ORDER BY price DESC;
-- Count records
SELECT COUNT(*) FROM myapp_product;
-- Average price
SELECT AVG(price) FROM myapp_product;
-- Insert record
INSERT INTO myapp_product (name, price, description, created_at)
VALUES ('Monitor', 299.99, '27-inch monitor', NOW());
-- Update record
UPDATE myapp_product SET price = 249.99 WHERE id = 1;
-- Delete record
DELETE FROM myapp_product WHERE id = 1;\qIn myapp/admin.py:
from django.contrib import admin
from .models import Product
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'price', 'created_at']
search_fields = ['name', 'description']
list_filter = ['created_at']python manage.py runserver- Open browser: http://127.0.0.1:8000/admin/
- Login with superuser credentials
- Click on "Products" to view/edit/delete records
- Search "pgAdmin 4" in Windows Start Menu
- Open the application
- Expand "Servers" in left panel
- Click on "PostgreSQL 16"
- Enter postgres password
- Expand "Databases" → "django_db"
- Expand "Schemas" → "public" → "Tables"
- Right-click on table → "View/Edit Data" → "All Rows"
pg_dump -U django_user -d django_db -f backup.sqlpsql -U django_user -d django_db -f backup.sql# Delete migration files (except __init__.py)
# Then run:
python manage.py makemigrations
python manage.py migratepython manage.py dbshell- Verify PostgreSQL service is running: Services → postgresql-x64-16
- Check firewall settings
- Verify credentials in settings.py
- Double-check username and password in settings.py
- Verify user exists:
psql -U postgresthen\du
- Create database:
psql -U postgresthenCREATE DATABASE django_db;
python manage.py migrate --fake-initial- Change port in settings.py or stop conflicting service