Python中如何精简处理不同Model对象的相似操作?
现在的项目中遇到一个问题,项目使用 flask 完成的,现在有几个数据表,有同一个 order 字段,并且都需要对这几个表的数据进行查询和对 order 字段的值进行调整。
低效率的方法是,为这几个表的 Model 类分别实现操作函数,但是这样写出来的代码,几个函数之间只有几个关键字是不一样的,感觉代码很冗余
所以请教大佬们,有什么精简的实现方法呢?
Python中如何精简处理不同Model对象的相似操作?
你把伪代码贴出来也好分析呀,空对空怎么讲呢
补充一下描述,python<br>def change_docorder():<br> reqdata = request.json<br> op = reqdata["op"]<br> docid = reqdata["docid"]<br><br> # 如果是上移文档顺序<br> if op == "up":<br> another = DocItem.query.filter(and_(DocItem.category_id == docitem.category_id,<br> DocItem.order < docitem.order)).order_by(DocItem.order.desc()).first()<br> if another is None:<br> return error_response(u"无法继续移动该文档顺序!")<br> tmp = another.order<br> another.order = docitem.order<br> docitem.order = tmp<br> another.save()<br> docitem.save()<br> elif op == "down":<br> another = DocItem.query.filter(and_(DocItem.category_id == docitem.category_id,<br> DocItem.order>docitem.order)).order_by(DocItem.order.asc()).first()<br> if another is None:<br> return error_response(u"无法继续移动该文档顺序!")<br> tmp = another.order<br> another.order = docitem.order<br> docitem.order = tmp<br> another.save()<br> docitem.save()<br> else:<br> return make_response(u"非法的操作!")<br> return make_response(json.dumps({<br> "status": "success",<br> "msg": u"修改文档顺序成功!"<br> }))<br>
这是针对 DocItem 这个 model 进行的调整顺序操作,还有其他的几个 model 对象需要进行相同的操作,如何如果都分别写一个函数来实现功能,最终代码只有类名 DocItem 是不一样的。
以上是对问题的补充描述。
这个你可以写一个闭包方法,把不同的参数传进去就可以,
v2ex 贴代码太不方便了,我把问题移至 segmentfault 了, https://segmentfault.com/q/1010000014261968


