0
0
Flaskframework~30 mins

Model definition in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Flask Model Definition
📖 Scenario: You are building a simple web app to store information about books in a library.Each book has a title, an author, and a year it was published.
🎯 Goal: Create a Flask model to represent a Book with the fields title, author, and year_published.
📋 What You'll Learn
Use Flask-SQLAlchemy to define the model
Create a model class named Book
Include fields: id (primary key), title (string), author (string), and year_published (integer)
💡 Why This Matters
🌍 Real World
Defining models is essential for building web apps that store and manage data like books, users, or products.
💼 Career
Understanding model definition with Flask and SQLAlchemy is a key skill for backend web developers working with Python.
Progress0 / 4 steps
1
Set up the Flask app and SQLAlchemy
Create a Flask app instance called app and initialize SQLAlchemy with db = SQLAlchemy(app).
Flask
Need a hint?

Import Flask and SQLAlchemy. Then create app = Flask(__name__) and db = SQLAlchemy(app).

2
Create the Book model class
Define a class called Book that inherits from db.Model.
Flask
Need a hint?

Define class Book(db.Model): and add columns for id, title, author, and year_published.

3
Add a string representation method
Add a __repr__ method to the Book class that returns a string like <Book 'Title' by Author>.
Flask
Need a hint?

Define def __repr__(self): and return a formatted string with the book's title and author.

4
Create the database tables
Call db.create_all() to create the tables in the database.
Flask
Need a hint?

Use with app.app_context(): then call db.create_all() to create tables.