Reputation: 6047
I have a web application where users can create and edit articles. Each article edit creates a new revision. I'm using SQLAlchemy as an ORM.
Now, every time I create an article this is what happens:
# Create the article
article = Article(...)
session.add(article)
session.flush()
# Create the revision
revision = Revision(article.id, ...)
session.add(revision)
session.flush()
# Set article's `current_revision_id` field to the revision's id
article.current_revision_id = revision.id
session.commit()
The reason I have to call flush() everytime is so I can get the IDs for the Article and Revision. Both the Article and Revision cannot be committed to the database until they have references to each other's ids.
My question is whether this is a sane thing to do. Is it possible that if many people are creating an article at the same time, the allocated IDs from the flush() calls become unsynced? Is this acceptable as a "transaction"?
Upvotes: 1
Views: 100
Reputation: 318498
Instead of using IDs in your code, use the relationship system of SQLAlchemy.
article = Article(...)
revision = Revision(article, ...)
article.current_revision = revision
session.add(article)
session.commit()
Upvotes: 4