简体   繁体   English

SQLAlchemy主键分配

[英]SQLAlchemy primary key assignement

I'm wondering where in the process of creating objects and storing them in the database the primary key gets assigned by SQLAlchemy. 我想知道在创建对象并将它们存储在数据库中的过程中,SQLAlchemy会分配主键。 In my app, when something happens I create an Event for that 'happening' and then create a notification for each user that needs to know about that Event. 在我的应用程序中,当发生某些事情时,我为发生的事件创建一个事件,然后为需要了解该事件的每个用户创建一个通知。 This all happens in the same method. 所有这些都以相同的方法发生。

The problem now is that the Notification references the Event. 现在的问题是,通知引用了事件。 Should I connect twice to the database to achieve this? 我应该两次连接到数据库以实现此目的吗? First to store the Event so it gets assigned a primary key and secondly to store the notification? 首先是存储事件,以便为它分配主键,其次是存储通知? Is it possible to only connect once to the database? 是否只能连接一次数据库?

So these steps should happen: 因此,应执行以下步骤:

  1. User does something 用户做某事
  2. Create an Event 建立活动
  3. Necessary? 必要? Store the Event in the database so I get a primary key to reference to 将事件存储在数据库中,以便获得要引用的主键
  4. Create a Notification that references the Event 创建引用事件的通知
  5. Store the Notification 储存通知

You don't need to worry about the primary-key to create the Notification just pass the Event object to the Notification , and commit . 您无需担心创建Notification的主键,只需将Event对象传递给Notification ,然后commit You're good to go. 你很好

SQLAlchemy doesn't assign the primary-key, it is the database that usually and implicitly does it for you, provided you have declared the table with something like this: id = Column(Integer, primary_key = True) . 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM