Given an instance of the SQLAlchemy class from Flask-SQLAlchemy,
db = SQLAlchemy(app)
- db is an interface for interacting with our database
- db.Model lets us create and manipulate data models. Models which are defined as classes mapped to tables within our database.
- db.session lets us create and manipulate database transactions. The context of a session which we use in order to interact with the database.
Declaring classes
- class MyModel(db.Model) will inherit from db.Model
- By inheriting from db.Model, we map from our classes to tables via SQLAlchemy ORM
Defining columns
- Within our class, we declare attributes equal to db.Column(…)
- db.Column takes datatype, primary_key, constraint, default
Table naming
- By default, SQLAlchemy will pick the name of the table for you, setting it equal to the lower-case version of your class’s name. Otherwise, we set the name of the table using
tablename = ''my_custom_table_name"
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username@localhost:5432/example'
db = SQLAlchemy(app)
# The Person class inherit from db.Model, we wound up linking and connecting to SQLAlchemy's mappings between classes and tables.
class Person(db.Model):
# By defult, SQLAlchemy will pick the name of the table for you and set it equal to the lowercase version of your class.
# But if you want to control the name of the table, you can do this way
__tablename__ = 'persons'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), nullable=False)
@app.route('/')
def index():
return 'Hello World!'
if __name__ == '__main__':
app.run()