Setting Up PostgreSQL for Django in Production
## Why PostgreSQL?
SQLite is great for development but PostgreSQL is the industry standard for production Django apps. It supports concurrent writes, full-text search, and JSONB fields natively.
## Install & Configure
```bash
sudo apt update && sudo apt install postgresql postgresql-contrib
sudo -u postgres psql
```
```sql
CREATE DATABASE clearcodes_db;
CREATE USER clearcodes_user WITH PASSWORD 'strongpassword';
GRANT ALL PRIVILEGES ON DATABASE clearcodes_db TO clearcodes_user;
```
## Django Settings
```python
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': config('DB_NAME'),
'USER': config('DB_USER'),
'PASSWORD': config('DB_PASSWORD'),
'HOST': config('DB_HOST', default='localhost'),
'PORT': config('DB_PORT', default='5432'),
}
}
```
## Connection Pooling with PgBouncer
For high-traffic sites, add PgBouncer in front of PostgreSQL to reuse connections:
```bash
sudo apt install pgbouncer
```
Configure `/etc/pgbouncer/pgbouncer.ini`:
```ini
[databases]
clearcodes_db = host=127.0.0.1 port=5432 dbname=clearcodes_db
[pgbouncer]
pool_mode = transaction
max_client_conn = 100
default_pool_size = 20
```
## Migrations
```bash
python manage.py migrate
python manage.py createsuperuser
```
Always run migrations in a transaction and keep backups before major schema changes.