[英]SQLAlchemy primary key assignement
我想知道在創建對象並將它們存儲在數據庫中的過程中,SQLAlchemy會分配主鍵。 在我的應用程序中,當發生某些事情時,我為發生的事件創建一個事件,然后為需要了解該事件的每個用戶創建一個通知。 所有這些都以相同的方法發生。
現在的問題是,通知引用了事件。 我應該兩次連接到數據庫以實現此目的嗎? 首先是存儲事件,以便為它分配主鍵,其次是存儲通知? 是否只能連接一次數據庫?
因此,應執行以下步驟:
您無需擔心創建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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.