Flask Tutorials: Defining Models

beginner
15 min

Flask Tutorials: Defining Models

Welcome to our comprehensive guide on Defining Models in Flask! 🎯

In this tutorial, we'll dive into the world of data modeling using Flask-SQLAlchemy, a popular extension for working with databases in Flask applications. Let's get started! 🚀

What are Models?

In a nutshell, a model is a representation of data in the form of classes that define the structure of the data. In Flask, models are used to interact with databases and manage data persistence. 📝

Why Do We Need Models?

Models help us define our data structures, enforce data integrity, and manage database interactions within our applications. They make it easier to perform common database operations, such as creating, reading, updating, and deleting data (CRUD operations). 💡

Installing Flask-SQLAlchemy

Before we start, make sure you have Flask-SQLAlchemy installed in your project. You can add it to your requirements using pip:

bash
pip install flask-sqlalchemy

Creating a Database Model

Now let's create our first model – a simple User 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) def __repr__(self): return f'<User {self.username}>'

In the above code, we first import SQLAlchemy and create a database instance. Then, we define the User class, which inherits from db.Model. We also define three columns – id, username, and email. The id column is primary key, which means each user will have a unique identifier. The unique and nullable parameters ensure that the username and email fields are unique and cannot be null.

We also provide a custom __repr__ method to create a user-friendly representation of the User model.

Database Initialization

To create the database tables based on our models, we'll use the create_all() method:

python
from app import app, db if __name__ == '__main__': app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db.create_all() app.run(debug=True)

In the above code, we set the database URI to a SQLite database file and call the create_all() method to create the users table based on our User model.

Quick Quiz
Question 1 of 1

Which method is used to create tables based on models in Flask-SQLAlchemy?

Working with Models

Now that we have our User model and table set up, let's learn how to interact with it using Flask-SQLAlchemy.

python
# Adding a new user user1 = User(username='testuser1', email='testuser1@example.com') db.session.add(user1) db.session.commit() # Fetching all users users = User.query.all() # Fetching a specific user user = User.query.filter_by(username='testuser1').first() # Updating a user user.username = 'updated_testuser1' db.session.commit() # Deleting a user db.session.delete(user) db.session.commit()

In the above examples, we create a new user, fetch all users and a specific user, update a user, and delete a user.

That's it for our Defining Models tutorial! In the next tutorial, we'll learn how to interact with our models using Flask-SQLAlchemy's ORM. 🎉

Stay tuned and keep learning with CodeYourCraft! 💡🎯