In depth: Item model
A Model is a representation of what our application deals with internally. Whenever two parts of our application communicate with one another, they'll do so mainly by using Models.
Code for models/item.py
from db import db
class ItemModel(db.Model):
__tablename__ = "items"
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
price = db.Column(db.Float(precision=2))
store_id = db.Column(db.Integer, db.ForeignKey("stores.id"))
store = db.relationship("StoreModel")
def __init__(self, name, price, store_id):
self.name = name
self.price = price
self.store_id = store_id
def json(self):
return {
"id": self.id,
"name": self.name,
"price": self.price,
"store_id": self.store_id,
}
@classmethod
def find_by_name(cls, name):
return cls.query.filter_by(name=name).first()
@classmethod
def find_all(cls):
return cls.query.all()
def save_to_db(self):
db.session.add(self)
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
The Models in our application can be boiled down to three things:
- They store some data for use within our application. This is what is defined in the
__init__
method—in case of theItemModel
that is thename
,price
, andstore_id
. - They define what columns they map to in our database. Often this includes all the parameters of the
__init__
method, but can also include more (such as theid
column, which is auto-incrementing and generated by our database). - It contains a few methods that allow us to interact with the database more easily.
ItemModel
methods
Searching for an item
Searching for an item is made easy because the ItemModel
is a SQLAlchemy Model
, so we can use Item.query
to interact with the table of items in our database.
For example, to find a specific item we define the find_by_name
method in the model, which does this:
@classmethod
def find_by_name(cls, name: str) -> "ItemModel":
return cls.query.filter_by(name=name).first()
From any other part of our application, we can then find an item in the database with that method:
ItemModel.find_by_name("chair")
And we would retrieve an item where the name column is "chair".
Getting all items from the database
To retrieve all items from the database, we can use:
ItemModel.find_all()
Saving an item to the database
To save an item to the database, we must first create an ItemModel
object, and then save it to the current database session:
my_item = ItemModel(name="Chair", price=15.99, store_id=1)
db.session.add(my_item)
db.session.commit()
But since the ItemModel already has a method that adds itself to the session and commits the connection, we can use that:
my_item = ItemModel(name="Chair", price=15.99, store_id=1)
my_item.save_to_db()
Deleting an item from the database
In a similar way to adding an item to the database, we can remove an item from the database session and then commit the connection:
my_item = ItemModel.find_by_name("Chair")
my_item.delete_from_db()
Returning an item to our client via the API
Normally REST APIs receive data and respond with data in JSON format (read What is JSON?). Our API is no different, so when we want to give a client data about an item, we must first convert it to JSON.
Because JSON is so similar to Python dictionaries, Flask-RESTful will convert from a Python dictionary into JSON for us automatically if it can. All we have to do to respond with JSON is give Flask-RESTful a dictionary with the data we want to send back.
That's what the ItemModel.json
method does: turn the data stored in the object into a Python dictionary.
my_item = ItemModel.find_by_name("Chair")
return my_item.json()