python - psycopg2:使用外键插入时出错

标签 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".

最佳答案

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

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

log_min_duration_statement = 0

关于python - psycopg2:使用外键插入时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49244643/

相关文章:

python - 简单示例 aes 256 加密

arrays - 在 PostgreSQL 中将图像文件保存为 bytea 并检索它们以在 HTML 模板上显示

django - 通过 Django 的 connection.cursor() 在自定义函数中调用 Postgresql date_trunc

javascript - 当我尝试在 Heroku 上使用 POSTGRESQL 更新数据库时,出现 22001 错误

Python+MySQL - 批量插入

python - 使用对每一行列的函数操作在 Pandas 数据框中创建新行的计算效率最高的方法?

python - 计算文件中某个三联体的数量(DNA 密码子分析)

c# - 如何将 Entity Framework 添加到控制台应用程序(包括图像)

mysql - 如何检查 MYSQL_HISTIGNORE 中的当前字符串?

database - 我应该升级 Apache Cassandra 吗?