我试图首先在表“lf_calculator_user”上插入一行,然后获取我刚刚插入的行的 ID,并使用该 ID 将其作为外键插入到表“lf_calculator_request”的另一条记录中。 这是我的代码:
if event["email"] is not None:
cursor.execute("INSERT INTO lf_calculator_user (email) VALUES (%(email)s) ON CONFLICT (email) DO UPDATE SET email = EXCLUDED.email;", event)
cursor.execute('SELECT LASTVAL()')
lastid = cursor.fetchone()[0]
if lastid is not None:
if event["amount"] is not None:
if event["date"] is not None:
cursor.execute('INSERT INTO lf_calculator_request (email_id, amount, invoice_due_date) VALUES ('+ str(lastid) +', %(amount)s, %(date)s);', event)
我收到一个奇怪的错误,说 email_id 不是表“lf_calculator_user”上的列,显然不是,它是作为外键的“lf_calculator_request”上的列。我错过了什么?
这里是错误:
psycopg2.IntegrityError: insert or update on table "lf_calculator_request" violates foreign key constraint "lf_calculatorrequest_email_id_fkey"DETAIL: Key (email_id)=(21) is not present in table "lf_calculator_user".
最佳答案
在 Postgresql 中尝试更详细的日志记录,问题可能会变得更加明显。 更新 postgresql.conf(并重启)
log_min_duration_statement = -1 # -1 禁用,0 记录所有语句
log_min_duration_statement = 0
关于python - psycopg2:使用外键插入时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244643/