Get models by ID from the database using SQLAlchemy
- Set metadata above
- Start writing!
- Create
start
folder - Create
end
folder - Create per-file diff between
end
andstart
(use "Compare Folders")
Using the model class's query
attribute, we have access to two very handy methods:
ItemModel.query.get(item_id)
gives us anItemModel
object from the database where theitem_id
matches the primary key.ItemModel.query.get_or_404(item_id)
does the same, but makes Flask immediately return a "Not Found" message, together with a 404 error code, if no model can be found with that ID in the database.
tip
When we use .get_or_404()
and nothing is found, this is the response from the API:
{"code": 404, "status": "Not Found"}
The status code of this response is also 404.
We're going to use .get_or_404()
repeatedly in our resources!
For now, and since we'll need an ItemModel
instance in all our Item
resource methods, let's add that:
resources/item.py
@blp.route("/items/<string:item_id>")
class Item(MethodView):
@blp.response(200, ItemSchema)
def get(self, item_id):
item = ItemModel.query.get_or_404(item_id)
return item
def delete(self, item_id):
item = ItemModel.query.get_or_404(item_id)
raise NotImplementedError("Deleting an item is not implemented.")
@blp.arguments(ItemUpdateSchema)
@blp.response(200, ItemSchema)
def put(self, item_data, item_id):
item = ItemModel.query.get_or_404(item_id)
raise NotImplementedError("Updating an item is not implemented.")
Similarly in our Store
resource:
resources/store.py
@blp.route("/stores/<string:store_id>")
class Store(MethodView):
@blp.response(200, StoreSchema)
def get(self, store_id):
store = StoreModel.query.get_or_404(store_id)
return store
def delete(self, store_id):
store = StoreModel.query.get_or_404(store_id)
raise NotImplementedError("Deleting a store is not implemented.")
With this, we're ready to continue!