从di保存关系sqlalchemy对象

2024-09-27 00:17:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用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)

Tags: 代码idfalsecolumnlocationintegerhotelnullable
1条回答
网友
1楼 · 发布于 2024-09-27 00:17:49

似乎您正在为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是这样的:

^{pr2}$

相关问题 更多 >

    热门问题