从字典中保存关系sqlalchemy对象

时间:2016-01-30 21:12:52

标签: 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)

1 个答案:

答案 0 :(得分:1)

您的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