Stephen Gilmore

Postgres Crash Course for Django Developers

Django September 10th, 2024 2 minute read.

I'm tired of Googling, prompting, and recalling a few Postgres basics to keep a Django project going.

This is written from the point of view of someone who owns a Mac or Linux and on Postgres version 15. I'm currently using postgres.app. In the examples, I'm using a fictitious name "zephyr" for the project name.

Create a new database:

psql -c "CREATE DATABASE zephyr"
psql -d zephyr -c "CREATE ROLE zephyr WITH LOGIN PASSWORD 'zephyrPW'"
psql -d zephyr -c "GRANT CREATE ON SCHEMA PUBLIC to zephyr"
psql -d zephyr -c "GRANT CREATE ON DATABASE zephyr to zephyr"

If you'll be testing, you may also need to add the permission to create a test database:

psql -d zephyr -c "ALTER USER zephyr CREATEDB"

Reference your database

Inside your .env folder, use -

DB_URL="postgres://zephyr:zephyrPW@localhost/zephyr"

Access the database

psql -U zephyr -d zephyr

Exporting data from a database

Table to CSV

Get into psql and then try:

\COPY app_model TO '/home/my/export.csv' WITH CSV HEADER;