Model (Flask-SQLAlchemy)

A model in Flask-SQLAlchemy is a Python class that subclasses db.Model and maps to a database table. Each class attribute defined as a db.Column becomes a column, and each instance becomes a row.

Flask

Models are the heart of the ORM approach: you describe your data once as a class, and SQLAlchemy translates between rows and Python objects. A User class with id, name, and email columns lets you write user.email instead of SQL.

Columns are declared with db.Column(type, **options), where options include primary_key, nullable, unique, and default. Relationships to other models use db.relationship plus a db.ForeignKey column to link rows together.

Creating a row is just instantiating the class and adding it to the session: db.session.add(User(name='Ana')) then db.session.commit(). Until you commit, nothing is written to the database.

Syntax

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)

Examples

Python

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(120), nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey("user.id"))

# create a row
db.session.add(Post(title="Hello"))
db.session.commit()

Learn it in a lesson

See also

Back to the Dictionary