Flask / Flask Models and Databases
Model Creation
In this tutorial, we will learn how to create models in Flask using SQLAlchemy. Models are classes that represent tables in the database.
Section overview
4 resourcesExplores Flask models, SQLAlchemy ORM, and database integration.
Model Creation in Flask using SQLAlchemy
Introduction
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
Step-by-Step Guide
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 SQLAlchemyapp = 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
Usermodel withid,username, andemailas 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.Columnand is given a type.primary_key,unique, andnullableare optional parameters that specify the characteristics of the column.
Code Examples
Let's walk through some examples of creating and interacting with a model.
-
Creating a Model
```python
from flask_sqlalchemy import SQLAlchemydb = 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
Usermodel is created withid,username, andemailfields. Theidfield is the primary key, andusernameandemailare unique and non-nullable. -
Adding a Record to the Model
```python
from app import User, dbuser = User(username='John', email='john@example.com')
db.session.add(user)
db.session.commit()
```In this example, a new
Userinstance is created, added to the session, and committed to the database.
Summary
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.
Practice Exercises
-
Create a
Postmodel withid,title,content, anduser_idfields. Theuser_idfield should be a foreign key to theidfield in theUsermodel. -
Add a
Postto thePosttable. -
Query all posts made by a specific user.
Solutions
-
Creating a
Postmodel.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
Postto thePosttable.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, Postuser = 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.
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article