将外键设置为 nullable=false?

Cas*_*sey 6 python sqlalchemy foreign-keys

您是否设置外键就nullable=false好像总是期望数据库中该列上的外键一样?

我正在使用 sqlalchemy 并使用所需的外键设置我的模型。这有时会导致我session.commit()更频繁地运行,因为我需要父模型具有 id 并完全创建,以便在 ORM 中构建子对象。什么被认为是最佳实践?我的模型如下:

class Location(Base):
    __tablename__ = 'locations'

    id = Column(Integer, primary_key=True)
    city = Column(String(50), nullable=False, unique=True)

    hotels = relationship('Hotel', back_populates='location')


class Hotel(Base):
    __tablename__ = 'hotels'

    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False, unique=True)
    phone_number = Column(String(20))
    parking_fee = Column(String(10))
    location_id = Column(Integer, ForeignKey('locations.id'), nullable=False)

    location = relationship('Location', back_populates='hotels')
Run Code Online (Sandbox Code Playgroud)

uni*_*rio 5

您无需做任何事情session.commit()即可获得身份证件;session.flush()会做。

更好的是,如果设置关系,则根本不需要获取 ID,因为 SQLalchemy 会计算出执行 s 的顺序INSERT。您可以简单地执行以下操作:

loc = Location(city="NYC", hotels=[Hotel(name="Hilton")])
session.add(loc)
session.commit()
Run Code Online (Sandbox Code Playgroud)

它会工作得很好。