psycopg2:使用外键插入时出错

时间:2018-03-12 21:25:32

标签: python database postgresql psycopg2

我想先在桌子上插一条线" 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".

1 个答案:

答案 0 :(得分:0)

在Postgresql中尝试更详细的日志记录,问题可能会变得更加明显。 更新postgresql.conf(并重新启动)

log_min_duration_statement = -1#-1被禁用,0记录所有语句

log_min_duration_statement = 0