2013-05-28 74 views
7

我正在嘗試使用sqlalchemy加載策略來加速我的查詢。在閱讀this之後,我意識到我在循環模板中的記錄時犯了錯誤。唯一的問題是,我得到這個錯誤:錯誤flask-sqlalchemy NameError:全局名稱'joinedload'未定義

NameError: global name 'joinedload' is not defined.

這是發生因爲我使用燒瓶SQLAlchemy的或時間我忘了進口的東西嗎?

Models.py:

inspection_violations = db.Table('inspection_violations', 
db.Column('violation_id', db.Integer, db.ForeignKey('violations.violation_number')), 
db.Column('inspection_id', db.Integer, db.ForeignKey('inspection.inspection_id')),) 

class Inspection(db.Model): 
    inspection_id = db.Column(db.Integer, primary_key=True) 
    violations = db.relationship('Violations', secondary=inspection_violations, backref=db.backref('inspection', lazy='dinamic')) 
    facility_id = db.Column(db.String(100), db.ForeignKey('facilities.branch_name')) 

class Violations(db.Model): 
    violation_number = db.Column(db.Integer, primary_key=True) 
    details = db.Column(db.Text) 

違反藍圖:

@violations_blueprint.route('/violations/<int:violation_number>') 
def show_single_violation(violation_number): 
    violation = Violations.query.options(joinedload('inspection')).get(violation_number) 
    return render_template('violations/single-violation.html' ,violation=violation) 

模板:

{% for inspection in violation.inspection %} 
    <p><a href="{{ url_for('inspection_blueprint.show_inspection', id=inspection.inspection_id) }}"> {{ inspection.facilities.branch_name }}</a></p> 
{% endfor %} 

給予一定的情況下我的模型有檢查記錄。每次檢查都有一次或多次違規行爲。而每違反了多次檢查

回答

13

那麼,錯誤消息指出joinedload沒有定義,那麼明顯的解決辦法是檢查,如果你輸入它,如果不是 -

from sqlalchemy.orm import joinedload 
+0

嘿比比,謝謝。我只是不確定它是否被導入或從哪裏導入,因爲我正在使用燒瓶擴展。 – Wilberto

+0

'flask-sqlalchemy'正在下面使用'sqlalchemy'。所以你可以隨時從中導入模塊。 –

+0

@Bibhas雖然你所說的是正確的100%,但Flask-SQLAlchemy也會將所有內容都導入到'db'中,所以你也可以使用它。 – jadkik94

0

在我的條件,它只是訂單問題

class Inspection(db.Model): 

class Violations(db.Model): 

inspection_violations =()  //wrong junction table position 

這不會起作用。因爲當您使用inspection_violations它尚未定義。並且還將報告了同樣的問題

只需更改訂單將使其工作

inspection_violations =() //right junction table position 

class Inspection(db.Model): 

class Violations(db.Model): 

這是做的正確方法。

相關問題