Skip to content

CRUD - Create Record

Creating records means:

  • instantiate a model
  • add it to the session
  • commit
diagram add, flush, commit: three different moments mermaid
Adding an object only puts it in the session. Nothing is sent to the database until a flush, which is when the INSERT actually runs and the primary key comes back. Commit flushes and then makes the transaction permanent. That is why an id is still None right after add, and why a rollback can throw away work that had already been flushed.
python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
 
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db"
 
db = SQLAlchemy(app)
 
 
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
 
 
with app.app_context():
    db.create_all()
 
    user = User(username="ravi")
    db.session.add(user)
    db.session.commit()
 
    print(user.id)  # id is available after commit
  • db.session holds pending changes
  • commit() finalizes the transaction

If something fails, you can:

python
db.session.rollback()
  • Forgetting commit() (data doesn’t persist)
  • Not handling IntegrityError (unique constraint violations)
  • Doing heavy DB work inside request handlers without optimization

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading