推荐学习书目
› 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 · Apr 9, 2018 · 2354 views
    This topic created in 3144 days ago, the information mentioned may be changed or developed.

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

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

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

    PressOne
    PressOne
    Apr 9, 2018 via Android
    1
    你把伪代码贴出来也好分析呀,空对空怎么讲呢
    xpke04
    xpke04
    OP
    Apr 9, 2018
    2
    补充一下描述,

    ``` 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
    PressOne
    Apr 9, 2018 via Android
    3
    这个你可以写一个闭包方法,把不同的参数传进去就可以,
    xpke04
    xpke04
    OP
    Apr 9, 2018
    4
    v2ex 贴代码太不方便了,我把问题移至 segmentfault 了, https://segmentfault.com/q/1010000014261968
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4395 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 06:04 · PVG 14:04 · LAX 22:04 · JFK 01:04
    ♥ Do have faith in what you're doing.