MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Defining Models & Column Constraints0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
5.1Flask-SQLAlchemy Setup & Engine Configuration5.2Defining Models & Column Constraints5.3Database Relationships (One-to-Many & Many-to-Many)5.4CRUD Operations, Query Filtering & Pagination5.5Database Schema Migrations with Flask-Migrate
HomeTutorialsFlaskDefining Models & Column Constraints
Database Relationships (One-to-Many & Many-to-Many)

Defining Models & Column Constraints

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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.


1. Declaring a Modern SQLAlchemy Model

In Flask-SQLAlchemy, models subclass db.Model. Attributes map to database columns via db.Column:

1from datetime import datetime, timezone
2from flask_sqlalchemy import SQLAlchemy
3 
4db = SQLAlchemy()
5 
6class Course(db.Model):
7 # Table name defaults to lowercase class name ('course'), but can be set explicitly:
8 __tablename__ = "courses"
9 
10 # Primary Key
11 id = db.Column(db.Integer, primary_key=True)
12 
13 # String & Text Columns with Constraints
14 title = db.Column(db.String(150), nullable=False, unique=True, index=True)
15 slug = db.Column(db.String(160), nullable=False, unique=True)
16 description = db.Column(db.Text, nullable=True)
17 
18 # Numeric Types
19 price = db.Column(db.Numeric(precision=10, scale=2), nullable=False, default=0.00)
20 rating = db.Column(db.Float, default=5.0)
21 
22 # Booleans & Integers
23 is_published = db.Column(db.BooleanField, default=False, nullable=False)
24 enrollment_count = db.Column(db.Integer, default=0)
25 
26 # Timestamps
27 created_at = db.Column(
28 db.DateTime(timezone=True),
29 default=lambda: datetime.now(timezone.utc),
30 nullable=False
31 )
32 updated_at = db.Column(
33 db.DateTime(timezone=True),
34 default=lambda: datetime.now(timezone.utc),
35 onupdate=lambda: datetime.now(timezone.utc)
36 )
37 
38 def __repr__(self):
39 return f"<Course id={self.id} title='{self.title}'>"

2. Common SQLAlchemy Column Data Types

SQLAlchemy TypeSQL EquivalentDescription
db.IntegerINTEGER32-bit signed integer
db.BigIntegerBIGINT64-bit integer (useful for high-volume transactions)
db.String(N)VARCHAR(N)Variable-length string with maximum length N
db.TextTEXTUnbounded text string (articles, blog bodies)
db.BooleanBOOLEANTrue or False
db.DateTimeTIMESTAMPPython datetime.datetime object
db.DateDATEPython datetime.date object
db.FloatFLOATFloating-point real numbers
db.Numeric(10,2)NUMERIC / DECIMALExact fixed-point numbers (financial currencies)

3. Essential Column Constraints

  • 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!

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What base class must every Flask-SQLAlchemy model inherit from?
Question 2
Why is db.Numeric preferred over db.Float for storing prices and financial currencies?
Question 3
Why should a timestamp default be passed as a callable (default=datetime.utcnow) rather than a called function (default=datetime.utcnow())?
Question 4
What does setting index=True on a column do in the underlying database?
Question 5
What does the __repr__ method do on a model class?
Next Lesson

Database Relationships (One-to-Many & Many-to-Many)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Flask-SQLAlchemy Setup & Engine ConfigurationDatabase Relationships (One-to-Many & Many-to-Many)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext