In the previous post, we created our database. Now it's time to populate it with some data. We created two tables, Restaurant and MenuItem to store the name of the restaurant and the menu item details respectively. In this post we will be performing the basic operations that are performed on the database inside a data-driven web application.
Creating Data
Using sqlalchemy, creating data is as easy as creating new objects in python.
So let's create another python script to fill some data into our empty database. Let's call it 'create_data.py'. Next, we need to add some dependencies, classes from our database_setup.py file. Type out the following lines of code. The description for each line of code is give in the comments
# We must first import the following dependencies:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Next we import the classes from the database_setup.py file we created in the previous blog
from database_setup import Base, Restaurant, MenuItem
# Then we connect our database to the program
engine = create_engine('sqlite:///restaurantmenu.db')
# Then we bind the 'Base' class to the 'engine'
Base.metadata.bind = engine
# Next I will create a sessionmaker object
# This establishes a link of communication between our code executions and the engine we just created
DBSession = sessionmaker(bind = engine)
session = DBSession()
SQLAlchemy executes database operations via an interface, called a session. A session allows us to write down all the commands that we we want to execute but does not send them to the database until we call the commit() method.
Now we are set to create our first restaurant and menu item.
# Creating Data
myFirstRestaurant = Restaurant(name="Balli Food Point")
session.add(myFirstRestaurant)
session.commit()
noodles = MenuItem(name = "Noodles",description = "Yummy spicy noodles with the$
session.add(noodles)
session.commit()
Reading Data
We can query all data objects from the tables using the query() method on the session object to read data. Run the following code in a python script and see what happens:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, Restaurant, MenuItem
engine = create_engine('sqlite:///restaurantmenu.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind = engine)
session = DBSession()
# Read data
print(session.query(MenuItem).all()) # Query all objects from MenuItem table
print(session.query(Restaurant).all()) # Query all objects from Restaurant table
firstResult = session.query(MenuItem).first() # Query first row from MenuItem
print(firstResult.name)
print(firstResult.description)
print(firstResult.price)
You should get an output similar to this:
devastating_dj@hp-2000-notebook:~/Blog$ python read_data.py
[<database_setup.MenuItem object at 0x7f4a80b42210>]
[<database_setup.Restaurant object at 0x7f4a80b33890>]
Noodles
Yummy spicy noodles with the goodness of veggies
Rs 40
Updating Existing Data
To update existing data inside database you need to follow four simple steps:
- Find Entry
- Reset Values
- Add to session
- session.commit()
# Find entry
results = session.query(Restaurant).filter_by(name = "Peppy Pizza") #This returns a list that we iterate over
for result in results:
print(result.name)
print(result.id)
# Search by id
query = session.query(Restaurant).filter_by(id = 1).one()
# Reset values
query.name = "New Peppy Pizza Place"
# Add to session
session.add(query)
session.commit()
Deleting Data
Just like while updating data we first find the entry that we want to update, in deleting we do the same except calling the add() method we use the the delete method on the session object.
# Search by id
query = session.query(Restaurant).filter_by(id = 1).one()
session.delete(query)
session.commit()
Congratulations! You have learned how to use an ORM to create a database and execute CRUD operations, setting the foundation for our interactive menu application.
Next, we will create a web server that will be able to perform these CRUD operations based on the request from the user.