通过SQLAlchemy将字典插入Postgres

时间:2017-11-03 05:59:51

标签: python postgresql dictionary sqlalchemy

我试图通过Python中的SQLAlchemy将字典加载到Postgres数据库中。当前存在的字典是:

FinalData = {'GAME_ID': {0: '0021600457', 1: '0021600457', 2: '0021600457', 3: 
'0021600457', 4: '0021600457', 5: '0021600457'}, 'TEAM_ID': {0: 1610612744, 1: 
1610612744, 2: 1610612744, 3: 1610612744, 4: 1610612744, 5: 1610612744}, 
'TEAM_ABBREVIATION': {0: 'GSW', 1: 'GSW', 2: 'GSW', 3: 'GSW', 4: 'GSW', 5: 
'GSW'}}

我编写了以下代码(根据我在这里和网上找到的其他教程/问题)。如果我只插入1条记录,我可以完成这项工作 - 因为我可以手动将属性分配给PlayerStats。但是由于字典有多个记录,我不知道如何将它们全部传递到会话语句中。

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

class PlayerStats(Base):
    __tablename__ = 'PlayerStats'

    GAME_ID = Column(String(10), primary_key=True)
    TEAM_ID = Column(String(10))
    TEAM_ABBREVIATION = Column(String(8))

###################################################
## I DON'T KNOW WHAT GOES HERE TO BRIDGE THE GAP ##
###################################################

engine = create_engine('postgres://.........')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
session.add(FinalData)  # I'M ASSUMING I NEED TO ITERATE OVER THIS #

我确定我遗漏了一些简单的内容,但如何将FinalData字典的所有内容传递到SQLAlchemy add语句?

1 个答案:

答案 0 :(得分:1)

您的FinalData结构由3个内部dicts组成,每个dicts由一些整数序列键入,因此您必须通过为子区域中的每个键创建一个新的PlayerStats对象来解压缩它。

在下面的示例中,我使用FinalData['GAME_ID']内部字典的整数键来搜索其他两个字母中的值以填充剩余的字段。

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String

Base = declarative_base()

class PlayerStats(Base):
    __tablename__ = 'PlayerStats'

    GAME_ID = Column(String(10), primary_key=True)
    TEAM_ID = Column(String(10))
    TEAM_ABBREVIATION = Column(String(8))

###################################################
FinalData = {'GAME_ID': {0: '0021600457', 1: '0021600457', 2: '0021600457', 3: 
'0021600457', 4: '0021600457', 5: '0021600457'}, 'TEAM_ID': {0: 1610612744, 1: 
1610612744, 2: 1610612744, 3: 1610612744, 4: 1610612744, 5: 1610612744}, 
'TEAM_ABBREVIATION': {0: 'GSW', 1: 'GSW', 2: 'GSW', 3: 'GSW', 4: 'GSW', 5: 
'GSW'}}
###################################################

engine = create_engine('postgres://.........')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()

for key in FinalData['GAME_ID']:
    p = PlayerStats()
    p.GAME_ID = FinalData['GAME_ID'][key]
    p.TEAM_ID = FinalData['TEAM_ID'].get(key)
    p.TEAM_ABBREVIATION = FinalData['TEAM_ABBREVIATION'].get(key)
    session.add(p)

session.commit()