0
0
Flaskframework~5 mins

Model definition in Flask

Choose your learning style9 modes available
Introduction

Models help you organize and store data in your app. They act like blueprints for your data.

When you want to save user information like names and emails.
When you need to keep track of items in a store or inventory.
When you want to record blog posts or comments.
When you want to connect data, like users and their orders.
When you want to easily add, update, or delete data in your app.
Syntax
Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class ModelName(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    field_name = db.Column(db.String(100), nullable=False)
    # add more fields as needed

Each model is a Python class that inherits from db.Model.

Fields are defined using db.Column with types like Integer or String.

Examples
This model stores users with unique usernames and emails.
Flask
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)
This model stores blog posts with a title and content.
Flask
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text, nullable=False)
Sample Program

This example creates a simple Flask app with a User model. It adds one user named 'alice' and then prints the username.

Flask
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)

with app.app_context():
    db.create_all()
    new_user = User(username='alice')
    db.session.add(new_user)
    db.session.commit()
    user = User.query.first()
    print(f'User: {user.username}')
OutputSuccess
Important Notes

Always call db.create_all() inside the app context to create tables.

Use nullable=False to make sure a field must have a value.

Unique fields prevent duplicate entries for that column.

Summary

Models define how data is stored in your app.

Each model is a class with fields as columns.

Use models to add, query, and manage data easily.