V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
xpke04
V2EX  ›  Python

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

  •  
  •   xpke04 · 2018-04-09 16:05:14 +08:00 · 1403 次点击
    这是一个创建于 2180 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

    PressOne
        1
    PressOne  
       2018-04-09 16:11:12 +08:00 via Android
    你把伪代码贴出来也好分析呀,空对空怎么讲呢
    xpke04
        2
    xpke04  
    OP
       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
        3
    PressOne  
       2018-04-09 16:26:29 +08:00 via Android
    这个你可以写一个闭包方法,把不同的参数传进去就可以,
    xpke04
        4
    xpke04  
    OP
       2018-04-09 16:30:06 +08:00
    v2ex 贴代码太不方便了,我把问题移至 segmentfault 了, https://segmentfault.com/q/1010000014261968
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3036 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 12:49 · PVG 20:49 · LAX 05:49 · JFK 08:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.