Install psycop2 on an M1 Macbook

Working with PostgreSQL and Python on a M1 MacBook

I recently needed to work with a PostgreSQL database in my Django projects. Normally I just use the default SQLite database as I am not doing anything complex.  

So I tried the basics of pip installing psycopg2, but kept running into the following errors:

ERROR: No matching distribution found for psycopg2-binary

or

ERROR: No matching distribution found for psycopg2

After searching around, I found a solution to my problem.  Here are the commands that I used to get working on my Macbook:

brew install postgresql
brew install libpq --build-from-source
brew install openssl

export LDFLAGS="-L/opt/homebrew/opt/openssl@1.1/lib -L/opt/homebrew/opt/libpq/lib"
export CPPFLAGS="-I/opt/homebrew/opt/openssl@1.1/include -I/opt/homebrew/opt/libpq/include"

pip3 install psycopg2

Note: I am using pyenv and python 3.9.5

I hope this helps in the future.