gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:25:12 26 4
gpt4 key购买 nike

我正在尝试使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com