- 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 (d efault:
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.
CREATEUSERdjango_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.
CREATEDATABASEdjango_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/Macsource 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:
fromdjango.dbimportconnectionconnection.ensure_connection()
print("Database connection successful!")
exit()In your app's models.py (e.g., myapp/models.py):
fromdjango.dbimportmodelsclassProduct(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):
returnself.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 shellfrommyapp.modelsimportProduct# Create single recordproduct1=Product.objects.create(
name='Laptop',
price=999.99,
description='High-performance laptop'
)
# Create multiple recordsProduct.objects.bulk_create([
Product(name='Mouse', price=25.50, description='Wireless mouse'),
Product(name='Keyboard', price=75.00, description='Mechanical keyboard'),
])# Get all recordsall_products=Product.objects.all()
forproductinall_products:
print(f"{product.name}: ${product.price}")
# Filter recordsexpensive=Product.objects.filter(price__gt=50)
# Get single recordproduct=Product.objects.get(id=1)
print(product.name)
# Get first/lastfirst=Product.objects.first()
last=Product.objects.last()
# Count recordscount=Product.objects.count()# Update single recordproduct=Product.objects.get(id=1)
product.price=899.99product.save()
# Update multiple recordsProduct.objects.filter(price__lt=30).update(price=29.99)# Delete single recordproduct=Product.objects.get(id=1)
product.delete()
# Delete multiple recordsProduct.objects.filter(price__lt=20).delete()
# Delete all records (use with caution!)Product.objects.all().delete()# Order byproducts=Product.objects.order_by('-price') # Descendingproducts=Product.objects.order_by('name') # Ascending# Limit resultsproducts=Product.objects.all()[:5] # First 5# Excludeproducts=Product.objects.exclude(price__lt=50)
# Complex queriesfromdjango.db.modelsimportQproducts=Product.objects.filter(
Q(price__lt=100) |Q(name__icontains='laptop')
)
# Aggregatefromdjango.db.modelsimportAvg, Sum, Countavg_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 recordsSELECT*FROM myapp_product;
-- Select specific columnsSELECT id, name, price FROM myapp_product;
-- Filter recordsSELECT*FROM myapp_product WHERE price >50;
-- Order resultsSELECT*FROM myapp_product ORDER BY price DESC;
-- Count recordsSELECTCOUNT(*) FROM myapp_product;
-- Average priceSELECTAVG(price) FROM myapp_product;
-- Insert recordINSERT INTO myapp_product (name, price, description, created_at)
VALUES ('Monitor', 299.99, '27-inch monitor', NOW());
-- Update recordUPDATE myapp_product SET price =249.99WHERE id =1;
-- Delete recordDELETEFROM myapp_product WHERE id =1;\qIn myapp/admin.py:
fromdjango.contribimportadminfrom .modelsimportProduct@admin.register(Product)classProductAdmin(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