def get_category_by_name(session, name):
'''
Get the category matching a name.
- Category name can be a simple name, or a full path to a category
inside the Category hierarchy.
- A full path consists of a sequence of category names separated by
'->' e.g. 'Refined->Gasoline'
'''
full_path = name.split('->')
if len(full_path) > 1:
# traverse the path
try:
cat_obj = (session.query(Category)
.filter(Category.name == full_path[0])
.filter(Category.parent == None)
.one())
for cat_name in full_path[1:]:
matching_catlist = [c for c in cat_obj.children
if c.name == cat_name]
if len(matching_catlist) > 1:
raise MultipleResultsFound('One matching child Category '
'required, found {} categories '
'matching the name {}'
.format(len(matching_catlist),
cat_name))
elif len(matching_catlist) == 0:
raise NoResultFound('child Category matching the name {} '
'not found'
.format(cat_name))
cat_obj = matching_catlist[0]
except Exception:
cat_obj = None
else:
# just a simple name
try:
cat_obj = (session.query(Category)
.filter(Category.name == name).one())
except Exception:
cat_obj = None
return cat_obj
评论列表
文章目录