【问题标题】:SQLAlchemy primary key assignementSQLAlchemy 主键分配
【发布时间】:2013-09-11 07:49:10
【问题描述】:

我想知道在创建对象并将它们存储在数据库中的过程中,主键是由 SQLAlchemy 分配的。在我的应用程序中,当发生某些事情时,我会为该“正在发生”创建一个事件,然后为需要了解该事件的每个用户创建一个通知。这一切都以相同的方法发生。

现在的问题是通知引用了事件。我应该两次连接到数据库来实现这一点吗?首先存储事件以便为其分配主键,然后存储通知? 是否可以只连接一次到数据库?

所以这些步骤应该发生:

  1. 用户做了某事
  2. 创建活动
  3. 需要吗?将事件存储在数据库中,以便我获得一个主键来引用
  4. 创建引用事件的通知
  5. 存储通知

【问题讨论】:

    标签: python sqlalchemy


    【解决方案1】:

    您无需担心创建Notification 的主键,只需将Event 对象传递给Notificationcommit。你可以走了。

    SQLAlchemy 不分配主键,它是数据库通常隐含地为您提供does it,前提是您已使用以下内容声明表: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()
    

    【讨论】:

    • 我想应该是: event = relationship("Event") ? :)
    • 啊..很好。它也应该是event_id = Column(Integer, ForeignKey("event.id"))。固定
    • 呃,我认为应该是 events.id
    • @arnoutaertgeerts 已修复!! ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多