An Object Relational Mapper (ORM) bridges the gap between object-oriented Python code and relational database tables. Instead of querying raw SQL tables, you define Python classes that subclass db.Model. Each class represents a database table, and each instance represents a row.
In Flask-SQLAlchemy, models subclass db.Model. Attributes map to database columns via db.Column:
| SQLAlchemy Type | SQL Equivalent | Description |
|---|---|---|
db.Integer | INTEGER | 32-bit signed integer |
db.BigInteger | BIGINT | 64-bit integer (useful for high-volume transactions) |
db.String(N) | VARCHAR(N) | Variable-length string with maximum length N |
db.Text | TEXT | Unbounded text string (articles, blog bodies) |
db.Boolean | BOOLEAN | True or False |
db.DateTime | TIMESTAMP | Python datetime.datetime object |
db.Date | DATE | Python datetime.date object |
db.Float | FLOAT | Floating-point real numbers |
db.Numeric(10,2) | NUMERIC / DECIMAL | Exact fixed-point numbers (financial currencies) |
primary_key=True: Establishes the unique identifier for table rows and creates an indexed primary key.nullable=False: Enforces a database-level NOT NULL constraint; inserting None raises an IntegrityError.unique=True: Enforces unique values across all rows (ideal for emails, usernames, slugs).index=True: Generates a B-tree database index for fast query lookup performance.default=value: Provides a default value when inserting a new record. Note: pass callables without parentheses (e.g. default=datetime.utcnow) so the function executes at insert time!db.Numeric preferred over db.Float for storing prices and financial currencies?default=datetime.utcnow) rather than a called function (default=datetime.utcnow())?index=True on a column do in the underlying database?__repr__ method do on a model class?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Flask-SQLAlchemy Setup & Engine Configuration | Database Relationships (One-to-Many & Many-to-Many) |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.