now there is a problem in the project. The project is completed in flask. Now there are several data tables with the same order field, and all need to query the data of these tables and adjust the value of the order field.
the inefficient way is to implement the operation functions for the Model classes of these tables respectively, but in the code written in this way, only a few keywords are different between the functions, which makes the code feel very redundant
. so ask the bosses, is there any concise way to achieve it?
post my code snippet first. The following is the operation code for the DocItem
class, and other Model classes need the same processing logic. The only difference between the final code is that DocItem
is replaced with the corresponding class name, which is very redundant.
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"")
-sharp
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""
}))