鍍金池/ 問答/Python  數(shù)據(jù)庫/ Flask Sqlalchemy 總是提示:is not bound to a

Flask Sqlalchemy 總是提示:is not bound to a Session; attri

我在視圖函數(shù)中調(diào)用了模型中的一個(gè)靜態(tài)方法:

@staticmethod
def getDots(pid='0', result=[]):
    current = Dot.query.filter_by(pid = pid).all()
    for v in current:
        result.append(v)
        Dot.getDots(v.id, result)
    return list(result)

視圖函數(shù):


@dot.route('/list', methods=['post', 'get'])
@login_required
def list():
    dots = Dot.getDots()
    return render_template('dot/list.html', dots=dots)
    

第一次進(jìn)入的時(shí)候數(shù)據(jù)都是正確的,如果再刷新一次就出現(xiàn)報(bào)錯(cuò):

clipboard.png

不知道為什么,第一次總是可以的,就是不能刷新

回答
編輯回答
編輯回答
嫑吢丕

我的理解是,你在你的 Dot 類中定義了一個(gè)即是靜態(tài)函數(shù)又是遞歸函數(shù)的 getDots()。這里涉及到你的遞歸問題。

出現(xiàn)以上錯(cuò)誤的原因是因?yàn)椋簊ession 已經(jīng)被提交,導(dǎo)致操作的 model 對(duì)象已經(jīng)不在當(dāng)前 session 中了。

使用下面的方法解決一下試試。

@staticmethod
def getDots(pid='0', result=[]):
    current = Dot.query.filter_by(pid = pid).all()
    for v in current:
        result.append(v)
        v = session.merge(v) # 新加內(nèi)容
        Dot.getDots(v.id, result)
    return list(result)

或者你改變一下你的遞歸方法。

2017年10月20日 17:52