我试图用sqlalchemy将一个对象保存到postgres数据库,但是遇到了问题。下面的代码可以工作,但是它没有保存位置“亚特兰大”的单个实例,并通过外键引用多个酒店,而是在locations表中反复保存该位置。在
如何设置我的代码,以便在locations表中有一个条目“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)
似乎您正在为for语句的每次迭代创建一个新的
Location
实例:更确切地说,我相信you want to attach all hotels to a single location是这样的:
^{pr2}$相关问题 更多 >
编程相关推荐