Python Friday #84: Working With Relational Data in SQLAlchemy ORM

The higher abstraction of SQLAlchemy ORM allows us to work with our objects as we usually do in Python. We do not need to think much about tables and relationships – SQLAlchemy ORM does this work for us.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Pre-requisites

The examples in this post build on top of the bookstore example from the last post for SQLAlchemy ORM.

We need once more the setup_db() and some helper methods to create our objects:

Important: It is easy to overlook, but when we create a relationship between two objects we use the whole object and not its id property. This allows SQLAlchemy ORM to do its magic in the background and we can add objects as we like.

 

Creating the example data

For the examples on how to retrieve data we need a publisher, two books, three authors and a bookdetail:

A few things to point out:

  • We need to call session.commit() at some time, otherwise SQLAlchemy will not persist our objects.
  • Whenever this method runs, it creates a new set of objects and with different primary key values.
  • For many-to-many relations we can use the collection property at either end (bookA.authors works as well as authorA.books)
  • The method returns multiple values with a tuple

 

A publisher and his books (one-to-many)

We can load the publisher and its books with this code:

The Mikado Method by <Publisher 43 (Manning Publications)>
Specification by Example by <Publisher 43 (Manning Publications)>

The method options(joinedload(“books”)) tells SQLAlchemy to eager load the Book table. This saves us a round trip to the database when we access the publisher.books property the first time. The next post will look at eager loading in more detail.

 

Authors of a book (many-to-many)

To show all authors of a book we can start at the book and load the authors with this command:

<Book 87 (The Mikado Method 9781617291210) 245>
      <Author 89 (Ola Ellnestam)>
      <Author 90 (Daniel Brolund)>
<Book 88 (Specification by Example 9781617290084) 249>
      <Author 91 (Gojko Adzic)>

 

Bookdetail for a book (one-to-one)

We can use this code to go from a book to its bookdetail:

<Book 87 (The Mikado Method 9781617291210) 245>
<BookDetails 87 (477597.jpg)>

 

Next

With only a few rows in our database we may not notice what SQLAlchemy ORM does in the background. This changes as soon as we have some real data and our application is unbearably slow. Next week we look at the difference between eager loading and lazy loading.

1 thought on “Python Friday #84: Working With Relational Data in SQLAlchemy ORM”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.