SQLAlchemy ORM Basics

Inserting Data

To create a new record using SQLAlchemy, we follow these steps:

  1. Create an object.
  2. Add the object to the session.
  3. Commit the session.

In SQLAlchemy, we interact with the database using session. Fortunately, we don’t need to create session manually, Flask-SQLAlchemy manages that for us. We access the session object as db.session. It is the session object which handles the connection to the database. The session object is also a handler for the transaction. By default, transaction implicitly starts and will remain open until the session is committed or rolled back.

Start the Python shell and create some model objects as follows:

Here we have created two Category objects. We can access attributes of an object using the dot(.) operator as follows:

Next, we add the objects to the session.

Adding objects to the session doesn’t actually writes them to the database, it only prepares the objects to be saved in the next commit. We can verify this by checking the primary key of the objects.

The value of id attribute of both the objects is None. That means our objects are not yet saved in the database.

Instead of adding one object to the session at a time, we can use add_all() method. The add_all() method accepts a list of objects to be added to the session.

Adding an object to the session multiple times doesn’t throw any errors. At any time, you can view the objects in the session using db.session.new.

Finally, to save the objects to the database call commit() method as follows:

Accessing the id attribute of the Category object will now return the primary key instead of None.

At this point, categories table in HeidiSQL should look like this:

Our newly created categories are not associated with any posts. So c1.posts and c2.posts would return an empty list.

Let’s create some posts now.

Instead of passing category while creating the Post object, we can also set it as follows:

Add the objects to the session and commit.

Access the posts attribute of the Category object again, this time you will get a non-empty list like this:

From the other side of the relationship, we can access the Category object to which the post belongs using the category attribute on the Post object.

Remember that, all of this became possible because of the relationship() directive in the Category model. We now have three posts in our database but none of them are associated with any tags.

Its time to create some tags. In the shell create Tag objects as follows:

This code creates three tag objects and commits them to the database. Our posts are still not connected to any tags. Here he how we can connect a Post object to a Tag object.

This commit adds the following five records in the post_tags table.

Our posts are now associated with one or more tags:

From the other way around, we can access posts which belongs to a tag as follows:

It is important to note that instead of first committing Tag objects and then associating it with Post objects, we could have done all this at once as follows:

Notice that in lines 11-13, we are only adding the Post objects to the session. The Tag and Post object are connected via a many-to-many relationship. As a result, adding a Post object to the session implicitly adds its associated Tag objects into the session as well. Even if you still add Tag objects manually to the session, you wouldn’t get any error.

Updating Data

To update an object simply set its attribute to a new value, add the object to the session and commit the changes.

Deleting Data

To delete an object use the delete() method of the session object. It accepts an object and marks it to be deleted in the next commit.

Create a new temporary tag named seo and associate it with the post p1 and p2 as follows:

This commit adds a total of 3 rows. One in the tags table and two in the post_tags table. In the database these three rows look like this:

Let’s now delete the seo tag:

This commit deletes all the three rows added in the previous step. However, it doesn’t delete the post to which the tag was associated.

By default, if you delete an object in the parent table (like categories) then the foreign key of its associated object in the child table (like posts) is set to NULL. The following listing demonstrates this behavior by creating a new category object along with a post object and then deleting that category object:

This commit adds two rows. One in the categories table and one in the posts table.

Now let’s see what happens when we delete a Category object.

This commit deletes the css category from the categories table and sets the foreign key (category_id) of its associated post to NULL.

On some occasions, you might want to delete all child records once parent records is deleted. We can achieve that by passing cascade='all,delete-orphan' to the db.relationship() directive. Open main2.py file and modify the db.relationship() directive in the Category model as follows (changes are highlighted):

flask_app/main2.py

From now on, deleting a category will also remove all the posts associated with it. Restart the shell for the changes to take effect, import necessary objects, and create a new category along with a post as follows:

Here is how the database should look after this commit.

Delete the category now.

After this commit database should look like this:

Querying Data

To query database we use the query() method of the session object. The query() method returns a flask_sqlalchemy.BaseQuery object which is just an extension of the original sqlalchemy.orm.query.Query object. The flask_sqlalchemy.BaseQuery object represents the SELECT statement that will be used to query the database. The following table lists some common methods of flask_sqlalchemy.BaseQuery class.

Method Description
all() returns the result of the query (represented by flask_sqlalchemy.BaseQuery) as a list.
count() returns the total number of records in the query.
first() returns the first result of the query or None, if there are no rows in the result.
first_or_404() returns the first result of the query or HTTP 404 Error, if there are no rows in the result.
get(pk) returns an object that matches the given primary key (pk), or None, if no such object is found.
get_or_404(pk) returns an object that matches the given primary key (pk), or HTTP 404 Error, if no such object is found.
filter(*criterion) returns a new flask_sqlalchemy.BaseQuery instance after applying the WHERE clause to the query.
limit(limit) return a new flask_sqlalchemy.BaseQuery instance after applying the LIMIT clause to the query.
offset(offset) return a new flask_sqlalchemy.BaseQuery instance after applying the OFFSET clause to the query.
order_by(*criterion) return a new flask_sqlalchemy.BaseQuery instance after applying ORDER BY clause to the query.
join() return a new flask_sqlalchemy.BaseQuery instance after creating SQL JOIN on the query.

all() method

In its simplest form, the query() method can take one or more model class or columns as arguments. The following code returns all the records from the posts table.

Similarly, the following code returns all the records from the categories and tags table.

To get the raw SQL used to query the database simply print the flask_sqlalchemy.BaseQuery object as follows:

In the preceding examples, the data is returned from all columns of the table. We can prevent this by passing the column names explicitly to the query() method as follows:

count() method

The count() method returns the number of results returned by the query.

first() method

The first() method returns only the first result of the query or None if the query returns zero results.

get() method

The get() method returns the instance which matches the primary key passed to it or None if no such object found.

get_or_404() method

Same as get() method but instead of returning None when no object found, it returns HTTP 404 Error.

filter() method

The filter() method allows us to filter our result by adding WHERE clause to the query. At the minimum, it accepts a column, an operator and a value. Here is an example:

This query returns all the posts where title is "Post 1". The SQL equivalent of the query is:

The string % (title_1) s in the WHERE clause is a placeholder and will be replaced by the actual value when the query is executed.

We can pass multiple filters to the filter() method and they will be joined together using SQL AND operator. For example:

This query returns all the posts whose primary key is greater than or equal to 1 but less than or equal to 2. Its SQL equivalent is:

first_or_404() method

Same as first() method but instead of returning None when the query returns no result, it returns HTTP 404 Error.

limit() method

The limit() method adds LIMIT clause to the query. It accepts the number of rows you want to return from the query.

The SQL equivalent of the above queries is as follows:

offset() method

The offset() method adds the OFFSET clause to the query. It accepts offset as an argument. It is commonly used with the limit() clause.

The SQL equivalent of the above query is as follows:

The strings % (param_1) s and % (param_2) s are placeholders for offset and limit respectively.

order_by() method

The order_by() method is used to order the result by adding ORDER BY clause to the query. It accepts column names on which the order should be based. By default, it sorts in ascending order.

To sort in descending order use db.desc() function as follows:

join() method

The join() method is used to create SQL JOIN. It accepts table name for which you want to create SQL JOIN.

This query is equivalent to the following SQL:

The join() method is commonly used to get the data from one or more table in a single query. For example:

We can create SQL JOIN for more than two table by chaining join() method as follows:

Let’s conclude this lesson by completing our Contact Form.

Recall that, In lesson Form Handling in Flask, we have created a Contact Form to receive feedback from users. As things stand, the contact() view function doesn’t save the submitted feedback to the database. It only prints the feedback to the console. To save the feedback to the database, we have to create a new table first. Open main2.py and add the Feedback model just below the Tag model as follows:

flask_app/main2.py

Restart the Python shell and invoke create_all() method of the db object to create the feedbacks table.

Next, modify the contact() view function as follows (changes are highlighted):

flask_app/main2.py

Start the server and visit http://127.0.0.1:5000/contact/, fill the form and submit feedback.

The submitted feedback in HeidiSQL should look like this:

Leave a Comment