In this tutorial, we will walk through the process of creating models in Flask using SQLAlchemy. A model in Flask represents a database table and can be used to interact with the table in a more Pythonic way.
Learning Outcomes
- Understand what Flask models are and how they are used with SQLAlchemy.
- Learn how to create and work with Flask models.
Prerequisites
- Basic understanding of Python
- Familiarity with Flask and SQLAlchemy
Flask models are classes in Python that extend the SQLAlchemy model class. These models represent a table in the database and the attributes of the class represent the columns in the table.
Setting up Flask-SQLAlchemy: Before creating the models, it is important to set up SQLAlchemy in your Flask application.
```python
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
```
In the above code, we first import the necessary modules, create an instance of Flask, configure the database, and initialize SQLAlchemy with the Flask app.
Creating a Model: Now that SQLAlchemy is set up, we can create a model. Let's create a User
model with id
, username
, and email
as the fields.
python
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)
Each field is created as an instance of db.Column
and is given a type. primary_key
, unique
, and nullable
are optional parameters that specify the characteristics of the column.
Let's walk through some examples of creating and interacting with a model.
Creating a Model
```python
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)
```
In this example, a User
model is created with id
, username
, and email
fields. The id
field is the primary key, and username
and email
are unique and non-nullable.
Adding a Record to the Model
```python
from app import User, db
user = User(username='John', email='john@example.com')
db.session.add(user)
db.session.commit()
```
In this example, a new User
instance is created, added to the session, and committed to the database.
In this tutorial, we learned how to set up Flask-SQLAlchemy, create a Flask model that represents a database table, and add a record to the table using the model.
To further your learning, consider exploring how to query the data from the table using the model and how to update and delete records.
Create a Post
model with id
, title
, content
, and user_id
fields. The user_id
field should be a foreign key to the id
field in the User
model.
Add a Post
to the Post
table.
Query all posts made by a specific user.
Solutions
Creating a Post
model.
python
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(140), nullable=False)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
Adding a Post
to the Post
table.
python
post = Post(title='My First Post', content='This is my first post.', user_id=1)
db.session.add(post)
db.session.commit()
Querying all posts made by a specific user.
```python
from app import User, Post
user = User.query.filter_by(username='John').first()
posts = Post.query.filter_by(user_id=user.id).all()
```
In these exercises, you learned how to create a model with a foreign key, add a record to the table using the model, and query the data using the model. For further practice, try updating and deleting records using the model.