def delete_category(category_name): """ DELETE - Delete category from database by name """ # Remove all the Items under this category first target_category = session.query(Category).filter_by( name=category_name).one() items_in_category_to_delete = session.query(Item).filter_by( category_id=target_category.id).all() for i in items_in_category_to_delete: delete_item(i.name) category_to_delete = session.query(Category).filter_by( name=category_name).delete() session.commit()
def get_category(category_name): """ READ - Retrieve one category from database by name """ result_category = session.query(Category).filter_by( name=category_name).one() return result_category
def update_category(category_name): """ UPDATE - updating category from request form into Database """ name = request.form['name'] category_to_update = session.query(Category).filter_by( name=category_name).one() category_to_update.name = name session.add(category_to_update) session.commit()
def update_item(item_id): """ UPDATE - updating item from request form into Database using id because user may change the name and description of the item from the form """ name = request.form['name'] description = request.form['description'] item_to_update = session.query(Item).filter_by(id=item_id).one() item_to_update.name = name item_to_update.description = description session.add(item_to_update) session.commit()
# Initialized some fake database and tables from tables import User, Category, Item from core import DBSession, engine, Base, session Base.metadata.create_all(engine) # Cleared everything before proceeding session.query(Category).delete() session.query(Item).delete() session.query(User).delete() ''' # Create Starter Categories category_soccer = Category('Soccer') category_basketball = Category('Basketball') category_baseball = Category('Baseball') category_snowboarding = Category('Snowboarding') # Create Starter Items item_soccerball = Item('Soccer Ball', 'An inflated ball used in playing a game of soccer.') item_snowboard = Item('Snowboard', 'A board resembling a short, broad ski, used for sliding downhill on snow') item_bindings = Item('Bindings', 'Special boots which help secure both feet of a snowboarder, who generally rides in an upright position.') # Put Items into few category, other categories are left item empty category_snowboarding.items = [item_snowboard, item_bindings] category_soccer.items = [item_soccerball] print "Database has been initialized with some fake data!"
def get_categories(): # Helper - Retrieve categories list from Database categories = session.query(Category).all() return categories
def get_category_set(): return session.query(Category).all()
def delete_item(item_name): """ DELETE - Delete item from database by name """ session.query(Item).filter_by(name=item_name).delete() session.commit()
def get_item(item_name): """ READ - Retrieve item from database by name """ result_item = session.query(Item).filter_by(name=item_name).one() return result_item