1

I'm wondering where in the process of creating objects and storing them in the database the primary key gets assigned by 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
arnoutaertgeerts
  • 2,232
  • 5
  • 29
  • 44

1 Answers1

2

You don't need to worry about the primary-key to create the Notification just pass the Event object to the Notification, and 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).

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()
Community
  • 1
  • 1
Bleeding Fingers
  • 6,993
  • 7
  • 46
  • 74