psycopg / psycopg2

PostgreSQL database adapter for the Python programming language

Home Page:https://www.psycopg.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Referencing another key with psycopg2

LvInSaNevL opened this issue · comments

  • OS: Ubuntu 20.04.3 LTS
  • Psycopg version: 2.9.7
  • Python version: 3.8.10
  • PostgreSQL version: Official Docker image
  • pip version: 20.0.2

Hey guys I have two tables in my database youtube.artists and youtube.song, and I would like the artist field in youtube.song to reference the name field in youtube.artists. The relationship looks something like this (sorry it's so big):

screenshot from dbdiagram.io

And my code looks like this currently (and side note if someone knows a better way to format this let me know, the data comes from an API in JSON format):

dbAuth_cursor.execute("""
                    with ins_artist as (
                        SELECT * FROM youtube.artists WHERE youtube_id = '{0}'
                        returning artistID
                    )
                    INSERT INTO youtube.song (mattfm_id, yt_id, published, genre, title, artist, description, viewcount, duration, thumbnail)
                    VALUES ('{1}', '{2}','{3}','{4}', '{5}', (REFERENCES artistID from ins_artist), '{7}', '{8}', '{9}');
                """.format(data.artist.yt_id, str(random.randint), data.yt_id, data.published, data.genre, data.title, data.description, data.viewcount, data.duration, data.thumbnail))

When I run that I get an error duplicate key value violates unique constraint "artists_name_key" which makes sense since the artist would already have been added into youtube.artist but that is what I believe I want.

I tried looking around but I couldn't find anything that was specific to psycopg2, it was more general PostgreSQL commands.

I am using the official Postgres docker image, Python 3.8.10, and psycopg2 2.9.7

Not a bug