While we used SQL to create our books database we thankfully will not need to use or know SQL to interact with our database. We’re going to use an Object Relational Mapper or ORM. An ORM makes it easy to query a database and retrieve data using a programming language. The data is also returned in a way which makes it easy to work with in Python.
The ORM we’re going to use is named peewee.
We can include peewee in our application app.py by uncommenting this line near the top:
from peewee import *
We also need to tell the ORM where the database we created is by uncommenting this line also near the top of the file:
db = SqliteDatabase('books.db')
There are lots of different ORMs to suit different tastes and some frameworks have a strong preference for using a specific ORM.
To use our books database in our application we need to define a model. A model basically tells our Python application what the corresponding table in our database looks like, including what the field names are and what type of data is stored in them. If our database had multiple tables, we would create multiple models.
We define our model with peewee by uncommenting these lines near the end of the file:
# This class represents a book, and tells our application about the structure of our database, including what types of data to expect from each field.
class Book(Model):
title = CharField()
description = CharField()
reason = CharField()
cover = CharField()
created_at = DateField()
# This is metadata tying this class to the database we defined earlier in this file
class Meta:
database = db
Notice that we don’t need to define the “id” field in the model - it is assumed to have an ID, and our ORM knows how to handle this field.