您无需担心创建主键Notification
只需将Event
对象传递给Notification
, 和commit
. 你可以走了。
SQLAlchemy 不分配主键,它是数据库通常隐含地为您执行此操作,前提是您已使用以下内容声明表id = Column(Integer, primary_key = True)
:
class Event(Base):
__tablename__ = "events"
id = Column(Integer, primary_key = True)
...
class Notification(Base):
__tablename__ = "notifications"
id = Column(Integer, primary_key = True)
event_id = Column(Integer, ForeignKey("events.id"))
event = relationship("Event")
...
def __init__(self, event):
self.event = event
notification = Notification(Event())
session.add(notification)
session.commit()