Python中针对多个Model类的相同操作的精简实现方式请教

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

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

所以请教大佬们,有什么精简的实现方法呢?
先贴一下我的代码片段,以下是针对DocItem类的操作代码,还有其他Model类需要同样的处理逻辑,最终代码的区别只有DocItem换成了对应的类名,很冗余。

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"指定文档不存在!")
    # 如果是上移文档
    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"修改文档顺序成功!"
    }))
阅读 3.7k
3 个回答

直接把model名做为参数传递

def change_docorder(item):
    result = item.query.filter(item.id==docid).one_or_none()

同样的逻辑,最好模块化,要不写成函数,要不写成类,我顺着 @prolifes 的思路,再往下细化一下。建议你把上面的函数的相同部分,再分解一下,分解成几个不同的函数,然后在类中进行调用即可。

新手上路,请多包涵

如果我做 我也顺着@prolifes的思路去做,如下:
docitem = DocItem.query.filter(DocItem.id==docid).one_or_none()

将docitem这个model对象当作参数,封装成函数调用

def handle_model(model=None):

if not model:
    return error_response(u"指定文档不存在!")

下面的直接可以copy了 如果部分不同的 可以试着当作参数使用

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏