SQLAlchemy is a deep and powerful thing made up of many layers. This cheat sheet sticks to parts of the ORM (Object Relational Mapper) layer,and aims to be a reference not a tutorial. That said, if you are familiar with SQL then this cheat sheet should get you well on your way to understanding SQLAlchemy.
Engines and Sessions
From sqlalchemy import or SampleModel.query.filter( or( SampleModel.id id, SampleModel.name name ) ).first. SQLAlchemy i About the Tutorial SQLAlchemy is a popular SQL toolkit and Object Relational Mapper.It is written in Python and gives full power and flexibility of SQL to an application developer. With a minimal and powerful web framework such as flask, combined with the power of sqlalchemy, you can get up and running within minutes. In fact, I’ve developed a prototype version called Tiddly that essentially does the same thing as above using just 172 lines of Python code. Flask-SQLAlchemy Cheat Sheet by Viel - Cheatography.com Created Date: 2209Z.
The docs for engines and sessions.
You can create a basic sqlite engine.
Or for something more advanced..
Given:
- user: scott
- password: tiger
- host: localhost
- database: test
The equivalent URI would be:
To interact with the engine you need to use a session. You can create a sessionusing a sessionmaker.
Models
An example of a basic model..
It's pretty easy to create the tables that correspond to your models.
Dropping all tables and data is just as simple.
Creating Data
The DocsOnce you have a session and have defined some models, you can create instancesof that model.
You can then stage the instance to your session (similar to how you stagechanges before committing them with git). Download gundam build fighters sub indo episode 15.
You can then commit everything in one hit.
Or roll back, if you don't want to save your changes.
Making Queries
Many-to-Many Relationships
This can be a tricky topic, so make sure to read the docs!
Many to Many adds an association table between two classes. The associationtable is indicated by the secondary argument to relationship(). Usually, theTable uses the MetaData object associated with the declarative base class, sothat the ForeignKey directives can locate the remote tables with which to link.
Now to link the two classes, you need to declare a relationship attribute.The secondary argument specifies the association table used. Theback_populates argument tells SqlAlchemy which column to link with when itjoins the two tables. It allows you to access the linked records as a listwith something like Parent.children.
Alternatively, you can use the backref argument when specifying therelationship for one class, this creates a virtual column in thecorresponding class that links back to the first one.
Flask and SQLAlchemy
In this post, we will build a very simple application using flask, sqlalchemy and postgres. The app will display a simple greeting by retrieving a value that is stored inside persons table. We will be using SQLAlchemy-ORM to define a model - which will create the persons table for us, and then, insert a row manually into the table, and finally retrieve the value from the table to display it.
Next, we will also learn how to run in an interactive mode which is very useful for debugging. Finally, I will provide an overview of querying the model object.
To get started, from your conda environment, install flask and flask-sqlalchemy.
pip3 install flaskpip3 install flask-sqlalchemy
Flask-SQLAlchemy is an extension for Flask that adds support for SQLAlchemy to your application. It aims to simplify using SQLAlchemy with Flask by providing useful defaults and extra helpers that make it easier to accomplish common tasks.
Basic structure of a flask app
app = Flask(__name__)sets the name of your app to the name of your module (“app” if “app.py” is the name of your file).- Using
@app.route: In this case,@app.routeis a Python decorator. Decorators take functions and returns another function, usually extending the input function with additional (“decorated”) functionality.@app.routeis a decorator that takes an input functionindex()as the callback that gets invoked when a request to route/comes in from a client. - Running a flask app:
FLASK_APP=app.py FLASK_DEBUG=true flask run
Alternative approach to run a Flask app using __main__:
Instead of using flask run, we could have also defined a method
Flask Sqlalchemy Query Cheat Sheet
Connecting to the database
Start postgres locally, and get the string postgresql://shravan:shravan@localhost:5432/interview
Configure your app
Use the db.Model - which lets you create and manipulate models. Or use the db.session to create and manipulate transactions.
Models which are defined as classes are mapped to tables within our database.
Given an instance of the SQLAlchemy class from Flask-SQLAlchemy db = SQLAlchemy(app):

- db is an interface for interacting with our database
db.Modellets us create and manipulate data modelsdb.sessionlets us create and manipulate database transactions in the context of a session.
Code for app.py:
The next thing we need to do is to actually create the tables in our database for all the models that we have declared using db.Model. In order to do this, we need to introduce db.create_all()
The four seasons by Vivaldi is always enjoyable and listening to a master viloinist play is a truly remarkable experience. The only way to improve the experience is to hear it live or to be Nishizaki. ![]()
db.create_alldetects models for us and creates tables for them, if those tables do not exist. If the tables do exist, then db.create_all doesn’t do anything for us.
This is important to know, since we will be calling db.create_all() multiple times within our Flask application.
From here, we can run our Flask application and expect to see that the model has been declared and also the tables for it has been created for.
Insert a row
Retrieve the value
Sqlalchemy Cheat Sheet Download
By default, SQLAlchemy will create a table based on the class name, by making it lowercase. You can specify a different name using the __tablename__ attribute.
Running SQLAlchemy interactively for debugging
We can experiment with our app using the interactive mode of the Python interpreter.
Adding a __repr__ to the model will print the values
Now when you run the app interactively, you can see the values inside those objects.
Inserting rows using db.session.add()
There’s another way of inserting records into our database, rather than entering a client like psql and using INSERT INTO SQL commands: we can call db.session from SQLAlchemy to create records using instances of our defined SQLAlchemy models.
In interactive mode, import db and your Person model. Then, create an instance of a Person, setting its attributes, and setting it equal to a variable person. We’re going to call db.session.add(), a method on the Session interface in SQLAlchemy, to add this object to a session, this will queue up a INSERT INTO persons (name) VALUES ('Veyd'); statement in a transaction that is managed by db.session.

We can then call db.session.commit()
and that person record will now exist in our persons table, within our database! You can double-check this in psql by running a SELECT * from persons; command from psql.
So, in summary, we can insert new records into the database using SQLAlchemy by running:
which will build a transaction for inserting in a person instance in our model/table, and persist it to the database upon calling commit().
Inserting multiple rows using db.session.add_all()
Model.query is the SELECT of SQL.
db.Model.query offers us the Query object. The Query object lets us generate SELECT statements that let us query and return slices of data from our database.
Query has method chaining. You can chain one query method to another (indefinitely), getting back more query objects, until you chain it with a terminal method that returns a non-query object like count(), all(), first(), delete(), etc.
The Query object can be accessed on a model using either:
MyModel.querydirectly on the model, ordb.session.query(Model)usingdb.session.queryinstead.
The most relevant and commonly used methods on the query:

The only thing here that needs a little explaining is the difference between filter_by and filter.
MyModel.query.filter_by(my_table_attribute='some value')MyModel.query.filter(MyOtherModel.some_attr='some value')
filter is similar to filter_by, but instead, you specify attributes on a given Model. It is more flexible than using filter_by itself, and is especially useful when querying from a joined table where you want to filter by attributes that span across multiple models.
Here’s quick reference that is useful SQLAlchemy Cheat Sheet
