In this section, we will delve into defining models using Flask-SQLAlchemy. Models are a crucial part of any web application as they represent the data structure and the relationships between different data entities. Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy, a powerful ORM (Object Relational Mapper) that allows you to interact with the database in an object-oriented way.

Key Concepts

  1. Model Definition: Creating classes that represent tables in the database.
  2. Fields/Columns: Defining attributes of the model that correspond to columns in the database table.
  3. Relationships: Establishing relationships between different models (e.g., one-to-many, many-to-many).
  4. CRUD Operations: Basic operations to create, read, update, and delete records.

Setting Up Flask-SQLAlchemy

Before defining models, ensure that Flask-SQLAlchemy is installed and configured in your Flask application.

# Install Flask-SQLAlchemy
pip install flask-sqlalchemy

Configuration

Add the following configuration to your Flask application:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'  # Example using SQLite
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

Defining a Model

A model in Flask-SQLAlchemy is a Python class that inherits from db.Model. Each attribute of the class represents a column in the database table.

Example: User Model

from datetime import datetime

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    image_file = db.Column(db.String(20), nullable=False, default='default.jpg')
    password = db.Column(db.String(60), nullable=False)
    posts = db.relationship('Post', backref='author', lazy=True)

    def __repr__(self):
        return f"User('{self.username}', '{self.email}', '{self.image_file}')"

Explanation

  • id: Primary key for the table.
  • username: A string field with a maximum length of 20 characters, must be unique and cannot be null.
  • email: A string field with a maximum length of 120 characters, must be unique and cannot be null.
  • image_file: A string field with a default value, cannot be null.
  • password: A string field for storing hashed passwords, cannot be null.
  • posts: A relationship field that links the User model to the Post model (one-to-many relationship).

Example: Post Model

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    content = db.Column(db.Text, nullable=False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    def __repr__(self):
        return f"Post('{self.title}', '{self.date_posted}')"

Explanation

  • id: Primary key for the table.
  • title: A string field with a maximum length of 100 characters, cannot be null.
  • date_posted: A datetime field with a default value of the current time, cannot be null.
  • content: A text field for the post content, cannot be null.
  • user_id: A foreign key linking to the User model, cannot be null.

Creating the Database

To create the database and the tables defined by your models, use the following commands in the Flask shell:

from yourapplication import db
db.create_all()

This will create the site.db file (or the database specified in your configuration) with the tables for the User and Post models.

Practical Exercise

Task

  1. Define a new model called Comment with the following fields:

    • id: Primary key.
    • content: Text field, cannot be null.
    • date_posted: DateTime field, default to current time, cannot be null.
    • user_id: Foreign key linking to the User model, cannot be null.
    • post_id: Foreign key linking to the Post model, cannot be null.
  2. Create the database and the tables.

Solution

class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False)
    date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)

    def __repr__(self):
        return f"Comment('{self.content}', '{self.date_posted}')"

# Create the database and tables
db.create_all()

Summary

In this section, we covered the basics of defining models using Flask-SQLAlchemy. We learned how to create models, define fields, establish relationships, and create the database tables. Understanding these concepts is crucial for building robust and scalable web applications with Flask. In the next section, we will explore performing CRUD operations with these models.

© Copyright 2024. All rights reserved