我正在尝试使用sqlalchemy将对象保存到Postgres数据库,但是遇到问题。下面的代码有效,但不是在位置表中一遍又一遍地保存位置,而不是保存位置“ Atlanta”的单个实例并通过外键引用多个酒店。
如何设置代码,以便在位置表中只有一个条目“亚特兰大”,并且有多个旅馆引用该位置?
这是我的代码的相关部分:
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)
看来您正在Location
for语句的每次迭代上创建一个新实例:
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
})
相反,我相信您希望将所有酒店附加到一个位置,例如:
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句