0
0
Flaskframework~5 mins

Why ORM simplifies database access in Flask

Choose your learning style9 modes available
Introduction

ORM helps you work with databases using simple code instead of complex SQL. It makes saving and getting data easier and faster.

When you want to avoid writing raw SQL queries.
When you need to work with database data as Python objects.
When you want to keep your code clean and easy to read.
When you want to switch databases without changing much code.
When you want to reduce errors from manual SQL syntax.
Syntax
Flask
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)

user = User(name='Alice')
db.session.add(user)
db.session.commit()

Define classes that represent tables in your database.

Use class attributes to define columns and their types.

Examples
This defines a Product table with id, title, and price columns.
Flask
class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    price = db.Column(db.Float)
This creates a new product and saves it to the database.
Flask
new_product = Product(title='Book', price=9.99)
db.session.add(new_product)
db.session.commit()
Sample Program

This Flask app uses ORM to create a User table, add a user named Alice, and then retrieve and print her name.

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), nullable=False)

with app.app_context():
    db.create_all()
    user = User(name='Alice')
    db.session.add(user)
    db.session.commit()
    retrieved_user = User.query.first()
    print(f'User name: {retrieved_user.name}')
OutputSuccess
Important Notes

ORM lets you think in Python objects, not SQL tables.

It handles database connections and queries behind the scenes.

Remember to commit changes to save data.

Summary

ORM simplifies database work by using Python classes and objects.

It reduces the need to write SQL directly.

It helps keep your code clean and easier to maintain.