ORM (Object-Relational Mapping) lets developers work with Python objects instead of writing SQL queries directly. It translates Python code into SQL behind the scenes, reducing manual SQL writing.
new_user = User(name='Alice')
session.add(new_user)
session.commit()Adding an object to the session and committing saves it to the database as a new row. The ORM handles the SQL INSERT automatically.
users = User.query.filter(User.age > 30).all()
filter() accepts expressions like User.age > 30, while filter_by() only accepts keyword arguments. Also, .all() returns all matching results.
user = User(name='Bob') session.add(user) session.commit() print(user.id)
After commit(), ORM updates the user object with the generated primary key id from the database, so user.id is accessible.
user = User(name='Carol', age=25) session.add(user) user.age = 26 session.commit() print(user.age)
ORM tracks changes to objects in the session. Changing user.age before commit updates the database and the object, so printing user.age shows 26.
