现在的项目中遇到一个问题,项目使用 flask 完成的,现在有几个数据表,有同一个 order 字段,并且都需要对这几个表的数据进行查询和对 order 字段的值进行调整。
低效率的方法是,为这几个表的 Model 类分别实现操作函数,但是这样写出来的代码,几个函数之间只有几个关键字是不一样的,感觉代码很冗余
所以请教大佬们,有什么精简的实现方法呢?
先贴一下我的代码片段,以下是针对DocItem
类的操作代码,还有其他Model类需要同样的处理逻辑,最终代码的区别只有DocItem
换成了对应的类名,很冗余。
def change_docorder():
reqdata = request.json
op = reqdata["op"]
docid = reqdata["docid"]
docitem = DocItem.query.filter(DocItem.id==docid).one_or_none()
if docitem is None:
return error_response(u"指定文档不存在!")
# 如果是上移文档
if op == "up":
another = DocItem.query.filter(and_(DocItem.category_id == docitem.category_id,
DocItem.order < docitem.order)).order_by(DocItem.order.desc()).first()
if another is None:
return error_response(u"无法继续移动该文档顺序!")
tmp = another.order
another.order = docitem.order
docitem.order = tmp
another.save()
docitem.save()
elif op == "down":
another = DocItem.query.filter(and_(DocItem.category_id == docitem.category_id,
DocItem.order>docitem.order)).order_by(DocItem.order.asc()).first()
if another is None:
return error_response(u"无法继续移动该文档顺序!")
tmp = another.order
another.order = docitem.order
docitem.order = tmp
another.save()
docitem.save()
else:
return make_response(u"非法的操作!")
return make_response(json.dumps({
"status": "success",
"msg": u"修改文档顺序成功!"
}))
直接把model名做为参数传递