python - 从字典中保存关系 sqlalchemy 对象

标签 python postgresql sqlalchemy

我正在尝试使用 sqlalchemy 将对象保存到 postgres 数据库,但遇到了问题。下面的代码有效,但它不是保存位置“亚特兰大”的单个实例,而是通过外键引用多个酒店,而是在位置表中一遍又一遍地保存位置。

如何设置我的代码,以便在位置表中有一个条目“亚特兰大”,多个酒店都指向该位置?

以下是我的代码的相关部分:

class Hotel(Base):
    __tablename__ = 'hotels'

    id = Column(Integer, primary_key=True)
    hotelName = Column(String)
    standardRate = Column(Numeric(6, 2))
    govtRate = Column(Numeric(6, 2))
    standardAvailable = Column(Boolean, nullable=False)
    govtAvailable = Column(Boolean, nullable=False)
    arrive = Column(Date, nullable=False)
    depart = Column(Date, nullable=False)
    updated = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
    location_id = Column(Integer, ForeignKey('location.id'))
    location = relationship('Location')

class Location(Base):
    __tablename__ = 'location'
    id = Column(Integer, primary_key=True)
    city = Column(String, nullable=False)

def scrape(location, arrive, depart, hotelIDs):
    hotels = []
    for id in hotelIDs:
      hotels.append({
            'hotelName': hotelName,
            'standardRate': standardRate,
            'govtRate': govtRate,
            'standardAvailable': standardAvailable,
            'govtAvailable': govtAvailable,
            'arrive': dateToISO(arrive),
            'depart': dateToISO(depart),
            'location': Location(city='Atlanta')
            })
    return hotels

def save_hotel(item):
    session = db_setup()

    hotel = Hotel(**item)
    session.commit()

hotels = scrape("atlanta", "02/20/2016", "02/21/2016", hotelIDs)
for hotel in hotels:
    save_hotel(hotel)

最佳答案

看来您在 for 语句的每次迭代中都创建了一个新的 Location 实例:

for id in hotelIDs:
    hotels.append({
        'hotelName': hotelName,
        'standardRate': standardRate,
        'govtRate': govtRate,
        'standardAvailable': standardAvailable,
        'govtAvailable': govtAvailable,
        'arrive': dateToISO(arrive),
        'depart': dateToISO(depart),
        'location': Location(city='Atlanta')  # <- new location instance here
        })

相反,我相信you want to attach all hotels to a single location更像这样:

location = Location(city='Atlanta')
# or if you already have Atlanta in your database:
# location = session.query(Location).filter_by(city='Atlanta').first() 

for id in hotelIDs:
    hotel = Hotel( ... )
    location.location.append(hotel)  # append hotel instance here
    ...

# now add to session and commit

关于python - 从字典中保存关系 sqlalchemy 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35107178/

相关文章:

java - 尝试将 Hibernate 连接到 Postgres 时出错

sql - 在不复制的情况下将表连接到自身

sql - 使用相同数据的两列

python - 如何使用 SQLAlchemy 只创建一张表?

python - 在 Python 中获取连接的 VPN 名称

Python - 如果键等于值,则从列表中删除字典

python - 如何使用 LoadLibrary 函数导入 dll 文件并使用 dll 文件中的函数?

python - sqlalchemy 检查对象是否在模型中

python - SQLAlchemy 急切/加入加载自引用一对一关系

python - 根据相似的两列对 pandas 数据框进行排序,但如果另一列具有值,则其中一列将为 NaN