鍍金池/ 問答/Python  數(shù)據(jù)庫(kù)/ Python中針對(duì)多個(gè)Model類的相同操作的精簡(jiǎn)實(shí)現(xiàn)方式請(qǐng)教

Python中針對(duì)多個(gè)Model類的相同操作的精簡(jiǎn)實(shí)現(xiàn)方式請(qǐng)教

現(xiàn)在的項(xiàng)目中遇到一個(gè)問題,項(xiàng)目使用 flask 完成的,現(xiàn)在有幾個(gè)數(shù)據(jù)表,有同一個(gè) order 字段,并且都需要對(duì)這幾個(gè)表的數(shù)據(jù)進(jìn)行查詢和對(duì) order 字段的值進(jìn)行調(diào)整。

低效率的方法是,為這幾個(gè)表的 Model 類分別實(shí)現(xiàn)操作函數(shù),但是這樣寫出來(lái)的代碼,幾個(gè)函數(shù)之間只有幾個(gè)關(guān)鍵字是不一樣的,感覺代碼很冗余

所以請(qǐng)教大佬們,有什么精簡(jiǎn)的實(shí)現(xiàn)方法呢?
先貼一下我的代碼片段,以下是針對(duì)DocItem類的操作代碼,還有其他Model類需要同樣的處理邏輯,最終代碼的區(qū)別只有DocItem換成了對(duì)應(yīng)的類名,很冗余。

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"無(wú)法繼續(xù)移動(dòng)該文檔順序!")
        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"無(wú)法繼續(xù)移動(dòng)該文檔順序!")
        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"修改文檔順序成功!"
    }))
回答
編輯回答
青檸

同樣的邏輯,最好模塊化,要不寫成函數(shù),要不寫成類,我順著 @prolifes 的思路,再往下細(xì)化一下。建議你把上面的函數(shù)的相同部分,再分解一下,分解成幾個(gè)不同的函數(shù),然后在類中進(jìn)行調(diào)用即可。

2018年7月27日 23:20
編輯回答
神經(jīng)質(zhì)

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

將docitem這個(gè)model對(duì)象當(dāng)作參數(shù),封裝成函數(shù)調(diào)用

def handle_model(model=None):

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

下面的直接可以copy了 如果部分不同的 可以試著當(dāng)作參數(shù)使用

2018年7月14日 23:59
編輯回答
黑與白

直接把model名做為參數(shù)傳遞

def change_docorder(item):
    result = item.query.filter(item.id==docid).one_or_none()
2018年2月2日 05:30