Defining Models in Flask
Key Concepts
- Models
- SQLAlchemy
- Database Schema
- ORM (Object-Relational Mapping)
- Model Relationships
Models
In Flask, models are Python classes that represent database tables. Each attribute of the model class corresponds to a column in the database table. Models are used to interact with the database, allowing you to perform CRUD (Create, Read, Update, Delete) operations.
SQLAlchemy
SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapping (ORM) library for Python. Flask-SQLAlchemy is an extension that simplifies the use of SQLAlchemy within Flask applications. It provides a high-level API for defining models and interacting with the database.
Database Schema
The database schema defines the structure of the database, including tables, columns, and relationships between tables. In Flask-SQLAlchemy, the schema is defined using model classes. Each model class represents a table, and its attributes represent columns.
ORM (Object-Relational Mapping)
ORM is a technique that maps database tables to Python objects. This allows you to interact with the database using Python code instead of writing raw SQL queries. Flask-SQLAlchemy provides an ORM layer that simplifies database operations by mapping model classes to database tables.
Model Relationships
Relationships define how tables are connected in the database. Common types of relationships include one-to-many, many-to-one, many-to-many, and one-to-one. In Flask-SQLAlchemy, relationships are defined using special attributes that link model classes together.
Example: Defining a Model
Below is an example of defining a simple model using Flask-SQLAlchemy. This model represents a "User" table with columns for "id", "username", and "email".
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) def __repr__(self): return f'<User {self.username}>'
Example: Defining Relationships
Here is an example of defining a one-to-many relationship between a "User" and a "Post" model. Each user can have multiple posts, but each post belongs to one user.
class Post(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False) content = db.Column(db.Text, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) user = db.relationship('User', backref=db.backref('posts', lazy=True)) def __repr__(self): return f'<Post {self.title}>'