简体   繁体   English

尝试将嵌套字典插入 Postgres 表 PsycoPg2 时出现 KeyError

[英]KeyError When Trying to Insert Nested Dictionary Into Postgres Table PsycoPg2

I'm getting this error KeyError: 'country.id' when I use psycopg2 to insert a list with a nested dictionary into a table in postgres:当我使用 psycopg2 将带有嵌套字典的列表插入到 postgres 中的表中时,出现此错误KeyError: 'country.id'

import psycopg2
import logging
from psycopg2.extras import LoggingConnection
def insert_fixture_data(match: dict):
    conn = psycopg2.connect(
        connection_factory=LoggingConnection, **db_settings)

    home_team = match['home_team']
    home_manager = home_team['managers']


    sql_updates = (
        "INSERT INTO manager (id,country_id,name,nickname,birth_date) VALUES (%(id)s,%(country.id)s,%(name)s,%(nickname)s,%(dob)s) ON CONFLICT DO NOTHING RETURNING id;"
    )

    try:
        cursor = conn.cursor()

        cursor.executemany(sql_updates, 
            home_manager)

    except Exception as error:
        print(error)
    finally:
        conn.close()

home_manager looks like this: home_manager看起来像这样:

[{'id': 665, 'name': 'Ivan Juric', 'nickname': None, 'dob': '1975-08-25', 'country': {'id': 56, 'name': 'Croatia'}}]

The schema and column names were correct when I checked in postgresql.我签入 postgresql 时模式和列名是正确的。

One possible solution.一种可能的解决方案。

Setup table设置表

create table manager(id integer, country_id integer, name varchar,nickname varchar, birth_date date);

Python code: Python 代码:

import psycopg2
con = psycopg2.connect("dbname=test user=postgres host=localhost port=5432")
sql_updates = (
        """INSERT INTO manager
    (id,country_id,name,nickname,birth_date) 
    VALUES (%(id)s,(country_id)s,%(name)s,%(nickname)s,%(dob)s) 
     ON CONFLICT DO NOTHING RETURNING id"""
    )

home_manager = [{'id': 665, 'name': 'Ivan Juric', 'nickname': None, 'dob': '1975-08-25', 'country': {'id': 56, 'name': 'Croatia'}}]
# Pull out nested dict. pop() removes the dict and key associated with
# the  'country' key.
country = home_manager[0].pop('country')
# Add back the country id as item with key 'country_id' and value 
# 'id' to the dict in home_manager.
home_manager[0].update({'country_id': country['id']})

cur = con.cursor()
cur.executemany(sql_updates, home_manager)
con.commit()

cur.execute("select * from manager")

cur.fetchone()
(665, 56, 'Ivan Juric', None, datetime.date(1975, 8, 25))


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM