It would be nice if we could lean on Django or psycopg2 for this.  There's no way this isn't already done somewhere by Django.