请教针对不同 Model 对象的相似处理的精简方法?

2018-04-09 16:05:14 +08:00
 xpke04

现在的项目中遇到一个问题,项目使用 flask 完成的,现在有几个数据表,有同一个 order 字段,并且都需要对这几个表的数据进行查询和对 order 字段的值进行调整。

低效率的方法是,为这几个表的 Model 类分别实现操作函数,但是这样写出来的代码,几个函数之间只有几个关键字是不一样的,感觉代码很冗余

所以请教大佬们,有什么精简的实现方法呢?

1420 次点击
所在节点    Python
4 条回复
PressOne
2018-04-09 16:11:12 +08:00
你把伪代码贴出来也好分析呀,空对空怎么讲呢
xpke04
2018-04-09 16:21:22 +08:00
补充一下描述,

``` python
def change_docorder():
reqdata = request.json
op = reqdata["op"]
docid = reqdata["docid"]

# 如果是上移文档顺序
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"修改文档顺序成功!"
}))
```

这是针对 DocItem 这个 model 进行的调整顺序操作,还有其他的几个 model 对象需要进行相同的操作,如何如果都分别写一个函数来实现功能,最终代码只有类名 `DocItem` 是不一样的。

以上是对问题的补充描述。
PressOne
2018-04-09 16:26:29 +08:00
这个你可以写一个闭包方法,把不同的参数传进去就可以,
xpke04
2018-04-09 16:30:06 +08:00
v2ex 贴代码太不方便了,我把问题移至 segmentfault 了, https://segmentfault.com/q/1010000014261968

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/445393

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX