arnoutaertgeerts
arnoutaertgeerts

Reputation: 2322

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. 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

Upvotes: 1

Views: 1908

Answers (1)

Bleeding Fingers
Bleeding Fingers

Reputation: 7129

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()

Upvotes: 2

Related Questions